1.安装
composer require maatwebsite/excel
安装后的设置
在config/app.php
中注册服务提供者到providers
数组:
Maatwebsite\Excel\ExcelServiceProvider::class,
同样在config/app.php
中注册门面到aliases
数组:
'Excel' => Maatwebsite\Excel\Facades\Excel::class,
第二步:使用laravel框架的artisan命令,新建excel导出脚本
php artisan make:export ProjectExport --model=Project
参数:
ProjectExport:脚本名(或者说是新生成的脚本文件名)
--model:引用的model
执行完上面的命令后,会在app/Exports目录下,新建对应的excel导出脚本。
第三步:编写脚本
<?php
namespace App\Exports;
use App\Models\Company;
use Maatwebsite\Excel\Concerns\FromArray; // 指定使用数组结构
use Maatwebsite\Excel\Concerns\WithMapping; // 设置excel中每列要展示的数据
use Maatwebsite\Excel\Concerns\WithHeadings; // 设置excel的首行对应的表头信息
use Illuminate\Contracts\Support\Responsable;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromCollection;
class CompanyExport implements FromCollection, WithMapping, WithHeadings, Responsable
{
use Exportable;
protected $data;
private $fileName;
public function __construct(array $data)
{
$this->data = $data; // 实例化该脚本的时候,需要传入要导出的数据
// $this->fileName = date('YmdHis') . '_Financial_project.xlsx'; // 指定导出的文件名
}
/**
* 将数组转为集合
* @return \Illuminate\Support\Collection
*/
public function collection()
{
return Company::all();
}
public function array(): array // 返回的数据
{
return $this->data;
}
public function map($value): array // 指定excel中每一列的数据字段
{
return [
$value['id'],
$value['company'],
$value['code'],
$value['types']['name'],
$value['industry'],
$value['city']
];
}
public function headings(): array // 指定excel的表头
{
return [
'id',
'企业名称',
'机构代码',
'企业分类',
'所属行业',
'企业分级',
];
}
}
public function export(Request $request)
{
$data= Company::with('types')->get()->toArray();
// dd($data);
//导出方法
return Excel::download(new CompanyExport($data), 'users.xlsx');
}