Search code examples
phpphpoffice

PHPOffice\Excel Styling Worksheet without a Spreadsheet Object


I'm having trouble styling cells in a worksheet object that doesn't yet belong to a spreadsheet object. Is this possible? It doesn't appear to be possible using the getStyle() method since this method calls functions in the parent spreadsheet. Maybe there is another method?

Worksheet class:

    class MyWorksheet extends \PHPOffice\PHPSpreadsheet\Worksheet\Worksheet {

        public function something() {
            $this->setCellValue('A1', 'Something');
            $this->getStyle('A1')->ApplyFromArray([
                'font' => ['bold' => true]
            ]);
         } 
    }

When something() is executed it results in a setActiveSheetIndex() on null exception.


Solution

  • Formatting cells

    A cell can be formatted with font, border, fill, ... style information. For example, one can set the foreground colour of a cell to red, aligned to the right, and the border to black and thick border style.

    Some examples:

    $spreadsheet->getActiveSheet()->getStyle('B3:B7')->getFill()
        ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
        ->getStartColor()->setARGB('FFFF0000');
    

    On the WorkSheet (your case)

    $worksheet->getParent()->getDefaultStyle()->applyFromArray([
        'font' => [
            'name' => $pValue->getFont()->getName(),
            'size' => $pValue->getFont()->getSize(),
        ],
    ]);
    

    OR

    Directly on the Spreadsheet

    $styleArray = [
        'font' => [
            'bold' => true,
        ],
        'alignment' => [
            'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_RIGHT,
        ],
        'borders' => [
            'top' => [
                'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
            ],
        ],
        'fill' => [
            'fillType' => \PhpOffice\PhpSpreadsheet\Style\Fill::FILL_GRADIENT_LINEAR,
            'rotation' => 90,
            'startColor' => [
                'argb' => 'FFA0A0A0',
            ],
            'endColor' => [
                'argb' => 'FFFFFFFF',
            ],
        ],
    ];
    
    $spreadsheet->getActiveSheet()->getStyle('A3')->applyFromArray($styleArray);
    

    https://phpspreadsheet.readthedocs.io/en/develop/topics/recipes/