Laravel Excel Import 記憶體不夠問題

大量資料匯入實出現 Allowed memory size of 1073741824 bytes exhausted 錯誤。

解法參考官網說明,載入並實做 Maatwebsite\Excel\Concerns\WithChunkReading 這個 class,並加上 chunkSize 方法,如下:
  1. use Maatwebsite\Excel\Concerns\ToCollection;
  2. use Maatwebsite\Excel\Concerns\WithChunkReading;
  3.  
  4. class UsersImport implements ToCollection, WithChunkReading
  5. {
  6. public function collection(Collection $rows)
  7. {
  8. $rows->each(function ($row, $key) {
  9. if ($key < 1 && $row[0] == '欄位標題') {
  10. return true;
  11. }
  12. });
  13. ...
  14. }
  15. public function chunkSize(): int
  16. {
  17. return 1000;
  18. }
  19. }
要特別注意第 9 行的判斷,如果使用 chunkSize 後每 1000 筆的第 1 筆都會被跳過,所以要多加上標題內容的判斷,以避免有資料沒有匯入。

留言