How to set background color for row in Laravel Excel?

OPV picture OPV · Aug 6, 2019 · Viewed 9.9k times · Source

I use Laravel Excel library and I have tried this code:

public function registerEvents(): array
{
    return [
        AfterSheet::class    => function(AfterSheet $event) {

            $styleArray =  array('fill' => array(
                'color' => array('rgb' => '000000')
            ));

            $cellRange = 'A1:W1'; // All headers
            $event->sheet->getDelegate()->getStyle($cellRange)->applyFromArray($styleArray);
        },
    ];
}

As result I get headers without black background color.

Also I tried this array settings:

$styleArray = [
                    'font' => [
                        'bold' => true,
                    ],
                    'background' => [
                        'color'=> '#000000'
                    ]
                ];

I use events, not creating. Please don't recommend not relevant answers

Answer

sss S picture sss S · Aug 7, 2019

Try this

$sheet->row(1, ['Col 1', 'Col 2', 'Col 3']); // etc etc
$sheet->row(1, function($row) { $row->setBackground('#CCCCCC'); });

You can also change $sheet->row() to $sheet->cell() and keep passing a row number as first argument.

$sheet->cell(1, function($row) { 
    $row->setBackground('#CCCCCC'); 
});

Then You can also use a more Excel-ish notation :

$sheet->cells('A1:D1', function ($cells) {
    $cells->setBackground('#008686');
    $cells->setAlignment('center');
});