laravel-excel官方文档:https://docs.laravel-excel.com/3.1
官方文档是英文版,可以在tampermonkey中添加google翻译脚本翻译网页
laravel-admin中安装laravel-excel参照官方文档:http://laravel-admin.org/docs/zh/model-grid-export#laravel-excel-v3
composer默认安装最新版本:composer require maatwebsite/excel
在/app/Admin/Extensions中新建自定义导出类,在控制器中grid方法中添加$grid->exporter(new PostsExporter());调用
<?php
namespace App\Admin\Extensions;
use App\Http\Model\News;
use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Concerns\FromCollection; // 导出集合:collection方法,主要处理导出数据
use Maatwebsite\Excel\Concerns\WithEvents; // 注册事件监听器:registerEvents方法
use Maatwebsite\Excel\Concerns\WithTitle; // 设置工作䈬名称
use Maatwebsite\Excel\Events\AfterSheet; // excel样式
class PostsExporter extends ExcelExporter implements FromCollection,WithTitle,WithEvents
{
protected $fileName = '新闻列表.xlsx'; //设置excel名称
protected $columns = [
'id' => 'ID',
'name' => '标题',
// 'listtype' => '类别',
];//第一行注释,但是有数组等格式数据的情况下会报错,新手办法是在collection方法中数据前标题数组
public function collection()
{
$news = News::all();
foreach ($news as &$val){
$val["listtype"] = json_encode($val["listtype"]);
$val["jsonstr"] = json_encode($val["jsonstr"]);
}
return $news;
}
public function registerEvents(): array
{
return [
AfterSheet::class => function(AfterSheet $event) {
// 合并单元格,具体方法可以参照phpexcel,因为laravel-excel是基于phpexcel的
//$event->sheet->getDelegate()->setMergeCells(['A1:B1']);
//$event->sheet->getDelegate()->getStyle('A1:A2')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
// 定义列宽度
$widths = ['B' => 20, 'C' => 20, 'D' => 20];
foreach ($widths as $k => $v) {
// 设置列宽度
$event->sheet->getDelegate()->getColumnDimension($k)->setWidth($v);
}
},
];
}
public function title(): string
{
return '新闻列表';
}
}