Laravel-excel3.1最基礎用法

daichongweb 發表於 2021-12-24
Laravel Excel

路由定義為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;
    }

    /**
     * 資料來源
     * @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;
    }
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結
DaiChongWeb