我从这里获得参考: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'
];
}
}
如果执行脚本,则结果如下:
我想在表格上方添加一些说明或标题,并希望对已售数量列和利润列进行求和
所以我想要这样的结果:
我已经阅读了文档并在Google中搜索,但找不到解决方法
有没有人可以帮助您?
更新
从此参考文献: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.
如何解决该错误?
答案 0 :(得分:1)
您必须实例化一个这样的数组:-
$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)。
您可以使用常规的单元格功能。