Laravel Excel Import 日期和公式問題
其實我在使用 Laravel Excel 匯入的時候遇過很多問題,但其實大部分的問題都可以在官方文件中找到答案,這一次遇到的兩個問題,其中一個最後也是在官方文件中找到的,只是我沒想到他的文章分類會在這麼奇怪的地方。
解決方式是載入 PhpOffice\PhpSpreadsheet\Shared\Date 這個 class,並使用裡面的 excelToDateTimeObject 方法,如下:
這時候要載入 Maatwebsite\Excel\Concerns\WithCalculatedFormulas 這個 class,並讓我們的 class implements 他即可。
這裏我真的要吐槽一下,為什麼官方文件是放在 Imports > Multiple Sheets 裡面,這真的很難找到啊啊啊。
一、日期匯入後變成數字
例如日期「2022/1/31」匯入之後會變成「44592」,如果不處理直接寫入資料庫可想而知不會是我們想要的。解決方式是載入 PhpOffice\PhpSpreadsheet\Shared\Date 這個 class,並使用裡面的 excelToDateTimeObject 方法,如下:
Date::excelToDateTimeObject($row['import_date']);
二、套公式的欄位匯入後是公式字串
我有一個欄位(A1)的值是由另外兩個欄位(B1&C1)字串相加而成,所以公式是「=B12&C1」,匯入後也會得到字串「=B12&C1」而不是我們期待的值。這時候要載入 Maatwebsite\Excel\Concerns\WithCalculatedFormulas 這個 class,並讓我們的 class implements 他即可。
這裏我真的要吐槽一下,為什麼官方文件是放在 Imports > Multiple Sheets 裡面,這真的很難找到啊啊啊。
三、範例程式
use Maatwebsite\Excel\Concerns\SkipsEmptyRows; use Maatwebsite\Excel\Concerns\ToCollection; use Maatwebsite\Excel\Concerns\WithCalculatedFormulas; use Maatwebsite\Excel\Concerns\WithHeadingRow; use PhpOffice\PhpSpreadsheet\Shared\Date; class FirstSheetImport implements ToCollection, WithHeadingRow, SkipsEmptyRows, WithCalculatedFormulas { public function collection(Collection $rows) { $rows->each(function ($row, $index) use (&$errorRows) { dd($row['to_date'], Date::excelToDateTimeObject($row['to_date'])); } } }
留言
張貼留言