| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 | <?phpnamespace App\Exports;use Illuminate\Support\Collection;use Maatwebsite\Excel\Concerns\FromCollection;use Maatwebsite\Excel\Concerns\WithCustomValueBinder;use Maatwebsite\Excel\Concerns\WithHeadings;use Maatwebsite\Excel\Concerns\WithStrictNullComparison;use Maatwebsite\Excel\Concerns\WithEvents;use Maatwebsite\Excel\Events\AfterSheet;use PhpOffice\PhpSpreadsheet\Cell\DefaultValueBinder;use PhpOffice\PhpSpreadsheet\Cell\Coordinate;class TableHeadExport extends DefaultValueBinder implements    WithCustomValueBinder,    FromCollection,    WithStrictNullComparison,    WithHeadings,    WithEvents{    protected $data;    protected $headers;    protected $headerComments; // 表头批注:键=表头名,值=批注内容    public function __construct($data, $headers = [], $headerComments = [])    {        $this->data = $data;        $this->headers = $headers;        $this->headerComments = $headerComments;    }    public function collection()    {        return new Collection($this->createData());    }    public function createData()    {        return $this->export();    }    public function headings(): array    {        return $this->headers;    }    private function export()    {        $list = [];        foreach ($this->data as $v) {            $list[] = $v;        }        return $list;    }    public function registerEvents(): array    {        return [            AfterSheet::class => function(AfterSheet $event) {                if (empty($this->headerComments)) {                    return; // 不传就不加批注                }                $sheet = $event->sheet->getDelegate();                foreach ($this->headers as $index => $headerName) {                    if (!isset($this->headerComments[$headerName])) {                        continue; // 该表头没设置批注                    }                    $columnLetter = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::stringFromColumnIndex($index + 1);                    $cell = $columnLetter . '1';                    $commentText = $this->headerComments[$headerName];                    // 创建批注                    $comment = $sheet->getComment($cell);                    $comment->getText()->createTextRun($commentText);                    $comment->setAuthor('系统提示');                    // 设置批注框大小(可调整数值)                    $comment->setWidth('200pt');   // 宽度                    $comment->setHeight('100pt');  // 高度                }            }        ];    }}
 |