ImportExcel.php 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace App\Common\Models;
  3. use Illuminate\Support\Collection;
  4. use Maatwebsite\Excel\Concerns\ToCollection;
  5. use Maatwebsite\Excel\Concerns\WithChunkReading;
  6. /**
  7. * 通用导入EXCEL文件对象
  8. * Class ImportExcel
  9. */
  10. class ImportExcel implements ToCollection, WithChunkReading
  11. {
  12. private $callback;
  13. private $readRows = 0;
  14. public function __construct(\Closure $callback)
  15. {
  16. $this->callback = $callback;
  17. }
  18. /**
  19. * 格式化日期
  20. * @param int $value
  21. * @param string $format
  22. */
  23. public static function transformDateTime(int $value, string $format = 'Y-m-d H:i:s')
  24. {
  25. if (!$value) {
  26. return '';
  27. }
  28. $value--;
  29. return date($format, strtotime("1900-01-00 00:00:00 +$value day"));
  30. }
  31. /**
  32. * @param Collection $collection
  33. */
  34. public function collection(Collection $collection)
  35. {
  36. if ($this->readRows == 0) {
  37. unset($collection[0]);
  38. $this->readRows += count($collection);
  39. }
  40. $this->callback->call($this, $collection);
  41. }
  42. /**
  43. * @return int
  44. */
  45. public function chunkSize(): int
  46. {
  47. return 1000;
  48. }
  49. }