TableHeadExport.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. <?php
  2. namespace App\Exports;
  3. use Illuminate\Support\Collection;
  4. use Maatwebsite\Excel\Concerns\FromCollection;
  5. use Maatwebsite\Excel\Concerns\WithCustomValueBinder;
  6. use Maatwebsite\Excel\Concerns\WithHeadings;
  7. use Maatwebsite\Excel\Concerns\WithStrictNullComparison;
  8. use Maatwebsite\Excel\Concerns\WithEvents;
  9. use Maatwebsite\Excel\Events\AfterSheet;
  10. use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;
  11. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  12. class TableHeadExport extends DefaultValueBinder implements
  13. WithCustomValueBinder,
  14. FromCollection,
  15. WithStrictNullComparison,
  16. WithHeadings,
  17. WithEvents
  18. {
  19. protected $data;
  20. protected $headers;
  21. protected $headerComments; // 表头批注:键=表头名,值=批注内容
  22. public function __construct($data, $headers = [], $headerComments = [])
  23. {
  24. $this->data = $data;
  25. $this->headers = $headers;
  26. $this->headerComments = $headerComments;
  27. }
  28. public function collection()
  29. {
  30. return new Collection($this->createData());
  31. }
  32. public function createData()
  33. {
  34. return $this->export();
  35. }
  36. public function headings(): array
  37. {
  38. return $this->headers;
  39. }
  40. private function export()
  41. {
  42. $list = [];
  43. foreach ($this->data as $v) {
  44. $list[] = $v;
  45. }
  46. return $list;
  47. }
  48. public function registerEvents(): array
  49. {
  50. return [
  51. AfterSheet::class => function(AfterSheet $event) {
  52. if (empty($this->headerComments)) {
  53. return; // 不传就不加批注
  54. }
  55. $sheet = $event->sheet->getDelegate();
  56. foreach ($this->headers as $index => $headerName) {
  57. if (!isset($this->headerComments[$headerName])) {
  58. continue; // 该表头没设置批注
  59. }
  60. $columnLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($index + 1);
  61. $cell = $columnLetter . '1';
  62. $commentText = $this->headerComments[$headerName];
  63. // 创建批注
  64. $comment = $sheet->getComment($cell);
  65. $comment->getText()->createTextRun($commentText);
  66. $comment->setAuthor('系统提示');
  67. // 设置批注框大小(可调整数值)
  68. $comment->setWidth('200pt'); // 宽度
  69. $comment->setHeight('100pt'); // 高度
  70. }
  71. }
  72. ];
  73. }
  74. }