Berikut ialah lajur tutorial Laravel untuk memperkenalkan anda kepada penggunaan paling asas Laravel-excel3.1 saya harap ia akan membantu anda!
Tapak web rasmi: https://docs.laravel-excel.com
Laluan ditakrifkan sebagai GET
Route::get('/export', [OrderController::class, 'export']);
Pemajuan pengawal
public function export(Request $request): BinaryFileResponse{ return Excel::download(new OrderExport($request->get('status', -1)), 'order.xlsx');}
Kod perniagaan
<?php namespace 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; } }
Cadangan berkaitan: Lima tutorial video Laravel terbaharu
Atas ialah kandungan terperinci Analisis ringkas tentang penggunaan asas Laravel-excel3.1. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!