批量将房东信息数据导出成excel下载到本地,在laravel使用第3方插件库来完成此项工作
插件库:maatwebsite/excel - Packagist
官网:Introduction | Laravel Excel
Superchargeed Excel 在 Laravel |中导出和导入Laravel Excel (laravel-excel.com)
导出步骤:🚀 5 minute quick start | Laravel Excel
安装对应的phpexcel插件
composer require maatwebsite/excel
在config/app.php
中注册服务提供者到providers
数组:
'providers' => [ | |
/* | |
* Package Service Providers... | |
*/ | |
Maatwebsite\Excel\ExcelServiceProvider::class, | |
] |
同样在config/app.php
中注册门面到aliases
数组:
'Excel' => Maatwebsite\Excel\Facades\Excel::class, | |
注:composer需要切源操作,否则下载将可能不会成功
安装成功后,就提供生成导出数据的命令,使用此命令生成导出数据文件
php artisan make:export FirmExport --model=Firm
生成对应的文件
添加表头:
namespace App\Exports; | |
use App\Models\Firm; | |
use Maatwebsite\Excel\Concerns\FromArray; // 指定使用数组结构 | |
use Illuminate\Contracts\Support\Responsable; | |
use Maatwebsite\Excel\Concerns\Exportable; | |
use Maatwebsite\Excel\Concerns\FromCollection; | |
use Maatwebsite\Excel\Concerns\WithHeadings; // 设置excel的首行对应的表头信息 | |
use Maatwebsite\Excel\Concerns\WithMapping; // 设置excel中每列要展示的数据 | |
class FirmExport implements FromCollection, WithHeadings, WithMapping, Responsable | |
{ | |
use Exportable; | |
protected $data; | |
private $fileName; | |
public function __construct(array $data) | |
{ | |
//实例化该脚本的时候,需要传入要导出的数据 | |
$this->data = $data; | |
} | |
/** | |
* 将数组转为集合 | |
* @return \Illuminate\Support\Collection | |
*/ | |
public function collection() | |
{ | |
return Firm::all(); | |
} | |
/** | |
* // 返回的数据 | |
* @return array | |
*/ | |
public function array():array{ | |
return $this->data; | |
} | |
/** | |
* 指定excel中每一列的数据字段 | |
* @param mixed $row | |
* @return array | |
*/ | |
public function map($row): array{ | |
return [ | |
$row['id'], | |
$row['q_name'], | |
]; | |
} | |
/** | |
* 指定excel的表头 | |
* @return array | |
*/ | |
public | |
function headings(): array{ | |
return [ | |
'ID', | |
'企业名称', | |
]; | |
} | |
} |
定义导出的路由
//exports导出 | |
Route::get('exports',[\App\Http\Controllers\UserController::class,'exports']); |
在列表页中指定导出按钮地址
<a href="{{url('exports')}}" class="btn btn-primary radius"> | |
<i class="Hui-iconfont"></i> 导出成excel</a> |
在控制器中实现导出功能
use Maatwebsite\Excel\Facades\Excel; | |
use App\Exports\FirmExport; | |
/** | |
* 导出excel | |
* @return \Symfony\Component\HttpFoundation\BinaryFileResponse | |
*/ | |
public function exports(){ | |
$data=Firm::get()->toArray(); | |
return Excel::download(new FirmExport($data),'firm.xlsx'); | |
} |