Laravel excel add complex headers to an export
Asked Answered
B

1

8

I need to export a sheet with a complex heading via Laravel Excel. I need a main heading and another sub-level heading after.

enter image description here

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?

Bascule answered 29/6, 2021 at 9:56 Comment(0)
B
16

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.

Bascule answered 29/6, 2021 at 23:30 Comment(2)
Good, I want to add a comment in a cell, can anybody help meGloriole
Think this may help you github.com/SpartnerNL/Laravel-Excel/issues/2138 @GlorioleBascule

© 2022 - 2024 — McMap. All rights reserved.