Search code examples
laravel-excelphpoffice-phpspreadsheet

It's possible to access $sheet in Import class of laravel-excel or get cell style from PHPOffice/PhpSpreadsheet


Imagine we are importing a excel, and using toCollection method.

And we need fill color of row or cell we using.

I can't figure how to access $sheet to get fill color or other properties of cell.

Anyway, i tried to use beforeImport event to access $currentWorkSheet of PHPOffice/PhpSpreadsheet to know what is color of cell

public static function beforeImport(BeforeImport $event)
    {
        for ($i = 1; $i < 10; $i++) {
            \Log::info(json_encode($event->getDelegate()->getActiveSheet()->getCell("A$i")->getValue()));
            \Log::info(json_encode($event->getDelegate()->getActiveSheet()->getStyle("A$i")->getFill()->exportArray()));
        }
    }

But for a column like this

enter image description here

I get this log that showing fill color is empty at all...

"AAAA"
{"fillType":"none","rotation":0}
"a2"
{"fillType":"none","rotation":0}
"a3"
{"fillType":"none","rotation":0}
"a4"
{"fillType":"none","rotation":0}
"a5"
{"fillType":"none","rotation":0}
"a6"
{"fillType":"none","rotation":0}
"a7"
{"fillType":"none","rotation":0}
"a8"
{"fillType":"none","rotation":0}
"a9"
{"fillType":"none","rotation":0}

Can anyone give me some idea why PHPOffice can't read cell properties?


Solution

  • Referring to Formatting cells section, you can export style as an array as follows:

    $styleArray = $spreadsheet->getActiveSheet()->getStyle('A3')->exportArray();
    

    Rather than

    $styleArray = $spreadsheet->getActiveSheet()->getStyle('A3')->getFill()->exportArray();
    

    You could give it a try, hope it helps!