路由定義為GET
Route::get('/export', [OrderController::class, 'export']);
控制器轉發
public function export(Request $request): BinaryFileResponse
{
return Excel::download(new OrderExport($request->get('status', -1)), 'order.xlsx');
}
業務程式碼
<?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;
}
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;
}
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結