我从这里得到了参考:https://laravel-excel.maatwebsite.nl/docs/3.0/getting-started/basics
所以我使用版本3
我的控制器是这样的:
public function exportToExcel(Request $request)
{
$data = $request->all();
$exporter = app()->makeWith(SummaryExport::class, compact('data'));
return $exporter->download('Summary.xlsx');
}
我的脚本导出为excel,如下所示:
namespace App\Exports;
use App\Repositories\ItemRepository;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\WithHeadings;
class SummaryExport implements FromCollection, WithHeadings {
use Exportable;
protected $itemRepository;
protected $data;
public function __construct(ItemRepository $itemRepository, $data) {
$this->itemRepository = $itemRepository;
$this->data = $data;
}
public function collection()
{
$items = $this->itemRepository->getSummary($this->data);
return $items;
}
public function headings(): array
{
return [
'No',
'Item Number',
'Sold Quantity',
'Profit'
];
}
}
如果脚本执行,结果如下:
我想在表格上方添加一些描述或标题,我想将销售数量列和利润列相加
所以我想要这样的结果:
我已阅读文档并在谷歌搜索,但我找不到解决方案
有人可以提供帮助吗?
更新
从这个参考:https://laravel-excel.maatwebsite.nl/docs/3.0/export/extending
我尝试添加:
....
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\BeforeExport;
use Maatwebsite\Excel\Events\BeforeWriting;
use Maatwebsite\Excel\Events\BeforeSheet;
use Maatwebsite\Excel\Events\AfterSheet;
class SummaryExport implements FromCollection, WithHeadings, WithColumnFormatting, ShouldAutoSize, WithEvents
{
...
public function registerEvents(): array
{
return [
BeforeExport::class => function(BeforeExport $event) {
$event->writer->setCreator('Patrick');
},
AfterSheet::class => function(AfterSheet $event) {
$event->sheet->setOrientation(\PhpOffice\PhpSpreadsheet\Worksheet\PageSetup::ORIENTATION_LANDSCAPE);
$event->sheet->styleCells(
'B2:G8',
[
'borders' => [
'outline' => [
'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THICK,
'color' => ['argb' => 'FFFF0000'],
],
]
]
);
},
];
}
}
在我上面的脚本中
但是存在这样的错误:
Method Maatwebsite\Excel\Sheet::styleCells does not exist
Method Maatwebsite\Excel\Sheet::setOrientation does not exist.
Method Maatwebsite\Excel\Writer::setCreator does not exist.
我该如何解决错误?
你必须像这样实例化一个数组: -
$export = [];
然后你必须使用array_push将数据推入其中: -
array_push($export, [
'No' => '',
'item'=>'',
'sold' =>'',
'profit' => ''
]);
然后你可以像这样附加你的计算: -
array_push($export,[' ','Items Count:', '=COUNTA(C2:C'.$Count.')' ,' ','Profit Sum:', '=SUM(D2:D'.$Count.')']);
如果你添加任何标题,$ count = count($ array + 1)。
并且您可以使用正常的细胞功能。