[phpexcel] Set Background cell color in PHPExcel

How to set specific color to active cell when creating XLS document in PHPExcel?

This question is related to phpexcel

The answer is


function cellColor($cells,$color){
    global $objPHPExcel;

    $objPHPExcel->getActiveSheet()->getStyle($cells)->getFill()->applyFromArray(array(
        'type' => PHPExcel_Style_Fill::FILL_SOLID,
        'startcolor' => array(
             'rgb' => $color
        )
    ));
}

cellColor('B5', 'F28A8C');
cellColor('G5', 'F28A8C');
cellColor('A7:I7', 'F28A8C');
cellColor('A17:I17', 'F28A8C');
cellColor('A30:Z30', 'F28A8C');

enter image description here


This always running!

$sheet->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setRGB('FF0000');


Here is how you do it in PHPSpreadsheet, the newest version of PHPExcel

$spreadsheet = new Spreadsheet();

$spreadsheet->getActiveSheet()->getStyle('A1:F1')->applyFromArray([
    'fill' => [
            'fillType' => Fill::FILL_SOLID,
            'startColor' => [
                'argb' => 'FFDBE2F1',
            ]           
    ],
]);

alternative approach:

$spreadsheet->getActiveSheet()
    ->getStyle('A1:F1')
    ->getFill()
    ->setFillType(Fill::FILL_SOLID)
    ->getStartColor()->setARGB('FFDBE2F1');

$objPHPExcel
    ->getActiveSheet()
    ->getStyle('A1')
    ->getFill()
    ->getStartColor()
    ->getRGB();

You can easily apply colours on cell and rows.

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

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

$objPHPExcel
->getActiveSheet()
->getStyle('A1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setRGB('colorcode'); //i.e,colorcode=D3D3D3

Seems like there's a bug with applyFromArray right now that won't accept color, but this worked for me:

$objPHPExcel
    ->getActiveSheet()
    ->getStyle('A1')
    ->getFill()
    ->getStartColor()
    ->setRGB('FF0000');

  $objPHPExcel->getActiveSheet()->getStyle('B3:B7')->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()->setARGB('FFFF0000');

It's in the documentation, located here: https://github.com/PHPOffice/PHPExcel/wiki/User-Documentation-Overview-and-Quickstart-Guide


This code should work for you:

 $PHPExcel->getActiveSheet()
        ->getStyle('A1')
        ->getFill()
        ->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
        ->getStartColor()
        ->setRGB('FF0000')

But if you bother using this over and over again, I recommend using applyFromArray.