在 PHPExcel 中创建 XLS 文档时,如何为活动单元设置特定颜色?
$sheet->getStyle('A1')->applyFromArray( array( 'fill' => array( 'type' => PHPExcel_Style_Fill::FILL_SOLID, 'color' => array('rgb' => 'FF0000') ) ) );
Source: http://bayu.freelancer.web.id/2010/07/16/phpexcel-advanced-read-write-excel-made-simple/
$objPHPExcel ->getActiveSheet() ->getStyle('A1') ->getFill() ->getStartColor() ->getRGB();
Seems like there's a bug with applyFromArray right now that won't accept color, but this worked for me:
applyFromArray
$objPHPExcel ->getActiveSheet() ->getStyle('A1') ->getFill() ->getStartColor() ->setRGB('FF0000');
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');
This always running!
$sheet->getActiveSheet()->getStyle('A1')->getFill()->getStartColor()->setRGB('FF0000');
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.
$objPHPExcel ->getActiveSheet() ->getStyle('A1') ->getFill() ->setFillType(PHPExcel_Style_Fill::FILL_SOLID) ->getStartColor() ->setRGB('colorcode'); //i.e,colorcode=D3D3D3
$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
Here is how you do it in PHPSpreadsheet, the newest version of PHPExcel
PHPSpreadsheet
PHPExcel
$spreadsheet = new Spreadsheet(); $spreadsheet->getActiveSheet()->getStyle('A1:F1')->applyFromArray([ 'fill' => [ 'fillType' => Fill::FILL_SOLID, 'startColor' => [ 'rgb' => 'FFDBE2F1', ] ], ]);
alternative approach:
$spreadsheet->getActiveSheet() ->getStyle('A1:F1') ->getFill() ->setFillType(Fill::FILL_SOLID) ->getStartColor()->setARGB('FFDBE2F1');
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'); });