Export.php 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. <?php
  2. namespace App\Exports;
  3. use Maatwebsite\Excel\Concerns\FromCollection;
  4. use Maatwebsite\Excel\Concerns\ShouldAutoSize;
  5. use Maatwebsite\Excel\Concerns\WithColumnFormatting;
  6. use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
  7. use Maatwebsite\Excel\Concerns\WithEvents;
  8. use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
  9. use Maatwebsite\Excel\Events\AfterSheet;
  10. use PhpOffice\PhpSpreadsheet\Cell\StringValueBinder;
  11. use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
  12. class Export extends StringValueBinder implements FromCollection,
  13. ShouldAutoSize,WithColumnFormatting,WithCustomValueBinder,WithStrictNullComparison,WithEvents
  14. {
  15. private $row;
  16. private $data;
  17. private $mergeCell;
  18. private $columnName;
  19. private $formatNumber;
  20. /*
  21. * $mergeCell $columnName :合并单元格所需参数;
  22. * $mergeCell 需要合并的位置数组以MAP形式存储 [开始行=>结束行]
  23. * $columnName 需要合并列 与合并行数结合使用ARRAY存储 ['A','B']
  24. */
  25. public function __construct($row,$data,$mergeCell=null,$columnName=null,$formatNumber=['D','H','I','L','O','Q','S','T','U','V'])
  26. {
  27. $this->row = $row;
  28. $this->data = $data;
  29. $this->mergeCell = $mergeCell;
  30. $this->columnName = $columnName;
  31. $this->formatNumber = $formatNumber;
  32. }
  33. public function collection()
  34. {
  35. $row = $this->row;
  36. $data = $this->data;
  37. //设置表头
  38. foreach ($row[0] as $key => $value) {
  39. $key_arr[] = $key;
  40. }
  41. //输入数据
  42. foreach ($data as $key => &$value) {
  43. $js = [];
  44. for ($i=0; $i < count($key_arr); $i++) {
  45. $js = array_merge($js,[ $key_arr[$i] => $value[ $key_arr[$i] ] ]);
  46. }
  47. array_push($row, $js);
  48. unset($val);
  49. }
  50. return collect($row);
  51. }
  52. public function registerEvents(): array
  53. {
  54. if ($this->mergeCell && $this->columnName){
  55. return [
  56. AfterSheet::class => function(AfterSheet $event){
  57. foreach ($this->columnName as $column){
  58. foreach ($this->mergeCell as $key=>$value){
  59. $event->sheet->getDelegate()->mergeCells($column.$key.':'.$column.$value);
  60. }
  61. }
  62. }
  63. ];
  64. }
  65. return [];
  66. }
  67. public function columnFormats(): array{
  68. $formatNumber = [];
  69. foreach ($this->formatNumber as $column){
  70. $formatNumber[$column] = NumberFormat::FORMAT_TEXT;
  71. }
  72. return $formatNumber;
  73. }
  74. }