---
# System prepended metadata

title: Laravel Excel 匯出時，日期欄位的轉換
tags: [Excel, Laravel]

---

###### tags: `Laravel` `Excel`

# Laravel Excel 匯出時，日期欄位的轉換

```php=
<?php 

namespace App\Exports;

use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
use App\Models\MyModel;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;

class MyModelExport implements FromQuery, WithMapping, WithColumnFormatting
{
    use Exportable;

    public function query()
    {
        return MyModel::select(...);
    }


    public function map($row): array
    {
        return [
            ...
            Date::dateTimeToExcel($row->created_at),    // column N
        ];
    }

    public function columnFormats(): array
    {
        return [
            'N' => 'yyyy-mm-dd hh:mm:ss',
        ];
    }
}
```