ExportExcel.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Common\Models;
  3. use Maatwebsite\Excel\Concerns\FromArray;
  4. use Maatwebsite\Excel\Concerns\WithColumnFormatting;
  5. use Maatwebsite\Excel\Concerns\WithEvents;
  6. use Maatwebsite\Excel\Concerns\WithHeadings;
  7. use Maatwebsite\Excel\Concerns\WithMapping;
  8. /**
  9. * 通用导出EXCEL文件对象
  10. * Class ExportObject
  11. */
  12. class ExportExcel implements FromArray, WithMapping, WithHeadings, WithEvents, WithColumnFormatting
  13. {
  14. private $dataList = [];
  15. private $headerMap = [];
  16. private $afterSheetStyle = [];
  17. private $columnFormats = [];
  18. /**
  19. * 构造函数
  20. * ExportObject constructor.
  21. * @param array $headerMap 头部描述数据
  22. * @param array $dataList 数据列表
  23. */
  24. public function __construct(array &$headerMap, array &$dataList, array &$afterSheetStyle = [], array &$columnFormats)
  25. {
  26. @ini_set("memory_limit", '512M');
  27. set_time_limit(60);
  28. $this->dataList = $dataList;
  29. $this->headerMap = $headerMap;
  30. $this->afterSheetStyle = $afterSheetStyle;
  31. $this->columnFormats = $columnFormats;
  32. }
  33. /**
  34. * 注册事件
  35. * @return array
  36. */
  37. public function registerEvents(): array
  38. {
  39. return $this->afterSheetStyle;
  40. }
  41. /**
  42. * 映射数据行
  43. * @param mixed $row
  44. * @return array
  45. */
  46. public function map($row): array
  47. {
  48. $o = [];
  49. foreach ($this->headerMap as $k => $v) {
  50. if (isset($row[$k])) {
  51. if ($row[$k] !== null && $row[$k] === 0) {
  52. $row[$k] = '0';
  53. } else if ($row[$k] === null) {
  54. $row[$k] = '';
  55. }
  56. } else {
  57. $row[$k] = '';
  58. }
  59. $o[] = $row[$k];
  60. }
  61. return $o;
  62. }
  63. /**
  64. * 返回头部
  65. * @return array
  66. */
  67. public function headings(): array
  68. {
  69. return array_values($this->headerMap);
  70. }
  71. /**
  72. * 数据源
  73. * @return array
  74. */
  75. public function array(): array
  76. {
  77. return $this->dataList;
  78. }
  79. public function columnFormats(): array
  80. {
  81. return $this->columnFormats;
  82. }
  83. }