Export.php 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. // TODO: Implement registerEvents() method.
  55. if ($this->mergeCell && $this->columnName){
  56. return [
  57. AfterSheet::class => function(AfterSheet $event){
  58. foreach ($this->columnName as $column){
  59. foreach ($this->mergeCell as $key=>$value){
  60. $event->sheet->getDelegate()->mergeCells($column.$key.':'.$column.$value);
  61. }
  62. }
  63. }
  64. ];
  65. }
  66. return [];
  67. }
  68. public function columnFormats(): array{
  69. $formatNumber = [];
  70. foreach ($this->formatNumber as $column){
  71. $formatNumber[$column] = NumberFormat::FORMAT_TEXT;
  72. }
  73. return $formatNumber;
  74. }
  75. }