这篇文章主要为大家展示了“Laravel-excel3.1怎么用”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Laravel-excel3.1怎么用”这篇文章吧。
路由定义为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; } public function collection(): Collection { $query = Order::query(); if ($this->status != -1) { $query->where('status', $this->status); } return $query->get(); } public function headings(): array { return [ '编号', '创建人', '中队长', '人员', '名称', '备注', '状态', '创建时间', '更新时间' ]; } public function columnFormats(): array { return [ 'H' => NumberFormat::FORMAT_DATE_YYYYMMDD, 'I' => NumberFormat::FORMAT_DATE_YYYYMMDD, ]; } 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), ]; } 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-excel3.1怎么用”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注编程网行业资讯频道!