1

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.

flint
  • 345
  • 5
  • 15

1 Answers1

3

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/

  • 1
    Arnold, all of these methods require that a parent spreadsheet. I was hoping to build the worksheet then assign it to a spreadsheet. It appears that this isn't possible. – flint Nov 07 '18 at 16:59
  • 1
    As I see it in the documentation https://phpspreadsheet.readthedocs.io/en/develop/topics/worksheets/#worksheets , this is how the phpspreadsheet works, you can really use a worksheet only if it is attached to a spreadsheet because only on the Spreadsheet you can set the style. "A worksheet is a collection of cells, formulae, images, graphs, etc. " – Arnold PÉTER Nov 14 '18 at 14:01