下面由laravel教程栏目给大家介绍关于laravel-excel3.1最基础用法,希望对大家有所帮助!
官网:https://docs.laravel-excel.com
路由定义为get
route::get('/export', [ordercontroller::class, 'export']);
控制器转发
public function export(request $request): binaryfileresponse{ return excel::download(new orderexport($request->get('status', -1)), 'order.xlsx');}
业务代码
<?phpnamespace app\exports;use app\models\order;use illuminate\support\collection;use maatwebsite\excel\concerns\fromcollection;use maatwebsite\excel\concerns\withcolumnformatting;use maatwebsite\excel\concerns\withheadings;use maatwebsite\excel\concerns\withmapping;use phpoffice\phpspreadsheet\shared\date;use phpoffice\phpspreadsheet\style\numberformat;/** * 派单导出 */class orderexport implements fromcollection, withheadings, withcolumnformatting, withmapping{ public $status; //接受参数 public function __construct(int $status) { $this->status = $status; } /** * 数据源 * @return collection */ public function collection(): collection { $query = order::query(); if ($this->status != -1) { $query->where('status', $this->status); } return $query->get(); } /** * 自定义表头 * @return string[] */ public function headings(): array { return [ '编号', '创建人', '中队长', '人员', '名称', '备注', '状态', '创建时间', '更新时间' ]; } /** * 设置单元格时间格式 * @return array */ public function columnformats(): array { return [ 'h' => numberformat::format_date_yyyymmdd, 'i' => numberformat::format_date_yyyymmdd, ]; } /** * 自定义数据列 * @param mixed $row * @return array */ public function map($row): array { return [ $row->id, $row->founder->name '无', $row->squadron->name '无', $row->player->name '无', $row->name, $row->remark ?: '无', $this->statusmap($row->status), date::datetimetoexcel($row->created_at), date::datetimetoexcel($row->updated_at), ]; } /** * 状态转化 * @param $status * @return string */ public function statusmap($status): string { switch ($status) { case 0: $statustext = '待处理'; break; case 1: $statustext = '处理中'; break; case 2: $statustext = '待审核'; break; case 3: $statustext = '已完成'; break; default: $statustext = '未知'; } return $statustext; }}
相关推荐:最新的五个laravel视频教程
以上就是简析laravel-excel3.1的基础用法的详细内容。