I need to export a sheet with a complex heading via Laravel Excel. I need a main heading and another sub-level heading after.
I'm trying like this,
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
class InvoicesExport implements FromQuery, WithHeadings
{
public function headings(): array
{
return [
'Account 1' =>[
"Account 1 id",
"Account 1 branch"
],
'Account 2' =>[
"Account 2 id",
"Account 2 branch"
],
];
}
}
But getting header columns like, [ "Account 1 id", "Account 1 branch" ]
is there a way to archive this task?
Finally, I managed to do it. Adding it since it will be useful for someone else.
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithCustomStartCell;
use Maatwebsite\Excel\Events\AfterSheet;
use Maatwebsite\Excel\Concerns\WithEvents;
use \Maatwebsite\Excel\Sheet;
class InvoicesExport implements FromCollection, WithHeadings, WithCustomStartCell, WithEvents{
public function startCell(): string
{
return 'A2';
}
public function registerEvents(): array {
return [
AfterSheet::class => function(AfterSheet $event) {
/** @var Sheet $sheet */
$sheet = $event->sheet;
$sheet->mergeCells('A1:B1');
$sheet->setCellValue('A1', "Account 1");
$sheet->mergeCells('C1:D1');
$sheet->setCellValue('C1', "Account 2");
$styleArray = [
'alignment' => [
'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
],
];
$cellRange = 'A1:D1'; // All headers
$event->sheet->getDelegate()->getStyle($cellRange)->applyFromArray($styleArray);
},
];
}
public function headings(): array
{
return [
"Account 1 id",
"Account 1 branch", \\here comma added
"Account 2 id",
"Account 2 branch"
];
}
}
Here I added startCell() to start from the second row. registerEvents() to merge and center align first-row cells with content.