将工作表传递到BeforeSheet事件Laravel Excel

ut6juiuv  于 2023-06-30  发布在  其他
关注(0)|答案(1)|浏览(98)

是否可以将$sheets传递给BeforeSheet事件?如果是,如何进行?我已经尝试过了,但是$sheets返回空数组,但是当在BeforeWriting事件中dd $sheets时,我得到了所有的工作表。

<?php

namespace Modules\CustomerTransactionSummaries\Exports;

class AccountabilityMultiSheetExport implements WithEvents
{
    use Exportable, RegistersEventListeners;

    protected $dateFrom, $dateTo, $customers, $farm;

    public function __construct(string $dateFrom, string $dateTo, array $customers, Model $farm)
    {
        $this->dateFrom = $dateFrom;
        $this->dateTo = $dateTo;
        $this->customers = $customers;
        $this->farm = $farm;
    }

    public function registerEvents(): array
    {
        $sheets = [];

        return [
            BeforeWriting::class => function (BeforeWriting $event) use (&$sheets) {
                $templateFile = new LocalTemporaryFile(storage_path('app/utilities/accountability.xlsx'));
                $event->writer->reopen($templateFile, \Maatwebsite\Excel\Excel::XLSX);

                // * Pass the $sheets to the BeforeSheet
                $sheets = $event->writer->getSheetNames();

                foreach ($sheets as $key => $value) {
                    $event->writer->getSheetByIndex($key)->export($event->getConcernable());
                }

                return $event->getWriter();
            },
            BeforeSheet::class => function (BeforeSheet $excel) use (&$sheets) {
                $sheet = $excel->sheet;

                $summary = new Summaries($this->dateFrom, $this->dateTo, $this->customers, $this->farm);
                $summary->printExcel($sheet->getTitle(), $sheet);
            },
        ];
    }
}
czq61nw1

czq61nw11#

不需要传递变量,因为您可以从这两个事件访问基础Spreadsheet类。
此外,事件函数是闭包,它们的结果不会被使用。(本质上它们是void),所以return语句不应该做任何事情。
您还应该能够从BeforeSheet事件访问PhpOffice\PhpSpreadsheet\Spreadsheet类。

return [
    BeforeWriting::class => function (BeforeWriting $event) {
        ...
        $sheets = $event->writer->getSheetNames();
        ...
    },
    BeforeSheet::class => function (BeforeSheet $event) {
        ...
        $sheets = $event->sheet->getParent()->getSheetNames();
        ...
    }
];

laravel-excel文档简要介绍了这一点:
| 有效载荷| Payload |
| --| ------------ |
| $event->writerMaatwebsite\Excel\Writer| $event->writer : Maatwebsite\Excel\Writer |
| $event->writerMaatwebsite\Excel\Writer| $event->writer : Maatwebsite\Excel\Writer |
| $event->sheet:|Maatwebsite\Excel\SheetMaatwebsite\Excel\Sheet |
| $event->sheet:|Maatwebsite\Excel\SheetMaatwebsite\Excel\Sheet |
这两个类Maatwebsite\Excel\SheetMaatwebsite\Excel\Writer使用trait Maatwebsite\Excel\DelegatedMacroable来 * 将 * 函数调用委托给它们的底层phpspreadsheet类。

  • Writer的委托类是PhpOffice\PhpSpreadsheet\Spreadsheet
  • Sheet的委托类是PhpOffice\PhpSpreadsheet\Worksheet\Worksheet

碰巧,PhpOffice\PhpSpreadsheet\Worksheet\Worksheet类有一个方法(getParent()),它返回底层的PhpOffice\PhpSpreadsheet\Spreadsheet类。

相关问题