18

Using PhpSpreadsheet, I want to set a white background to the excel cell.

$cells = 'A1';
$spreadsheet
    ->getActiveSheet()
    ->getStyle($cells)
    ->getFill()
    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
    ->getStartColor(' #FFFFFF')
    ->setARGB('#FFFFFF');

This code makes the cell background black even if I set this white RGB color value: #FFFFFF.

The result I would like to achieve:

BEFORE

AFTER

totymedli
  • 29,531
  • 22
  • 131
  • 165
Premlatha
  • 1,676
  • 2
  • 20
  • 40
  • Can anyone show me what is wrong with this code.. '$sheet->getStyle('A1:E3')->applyFromArray(array(       'fill' => array(           'type' => Fill::FILL_SOLID,           'color' => array('rgb' => 'E5E4E2' )       ));' – Premlatha Mar 09 '19 at 03:40

2 Answers2

45

You don't have to include the # symbol when you specify the ARGB for PhpSpreadsheet. These solutions will be able to set the cell background to white:

Cell by cell

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

Range of cells

$spreadsheet
    ->getActiveSheet()
    ->getStyle('A1:A5')
    ->getFill()
    ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
    ->getStartColor()
    ->setARGB('ffffff');
totymedli
  • 29,531
  • 22
  • 131
  • 165
Premlatha
  • 1,676
  • 2
  • 20
  • 40
12

By using a style array to set few styles at once:

styleArray = array(
            'borders' => array(
                'outline' => array(
                    'borderStyle' => Border::BORDER_THICK,
                    'color' => array('argb' => '00000000'),
                ),
            ),
            'fill' => array(
                'fillType' => Fill::FILL_SOLID,
                'startColor' => array('argb' => 'FF4F81BD')
            )
        );
$spreadsheet->getActiveSheet()->applyFromArray($styleArray);

In some examples, we find 'fill' instead of 'fillType'. Perhaps it depends on version of phpSpreadsheet. Another variant is 'color' instead of 'startColor'.

  • 1
    There seems to be a getStyle() missing in the last line. For me it's always been: $spreadtsheet->getActiveSheet->getStyle($cellOrRange)->applyFromArray($styleArray); – loonighan Jun 04 '22 at 08:53