Set an background color to a list of colums

Topics: Developer Forum, User Forum
Oct 19, 2009 at 3:17 PM

How to set background color to colums: A1:Z1 from an array, or as small source code as possible.
 
I can do this when setting borders:
<?php
$sharedStyleTitles = new PHPExcel_Style();
$sharedStyleTitles->applyFromArray(
	array('borders' => array(
		'bottom'=> array('style' => PHPExcel_Style_Border::BORDER_THIN),
		'top'	=> array('style' => PHPExcel_Style_Border::BORDER_THIN),
		'left'	=> array('style' => PHPExcel_Style_Border::BORDER_THIN),
		'right'	=> array('style' => PHPExcel_Style_Border::BORDER_THIN)
		)
 ));
$objPHPExcel->getActiveSheet()->setSharedStyle($sharedStyleTitles, 'A'.$sk.':Z'.$sk);
?>

But I don't know how to also add not only borders but and a background colors.

I know only the way when I add it one by one to each column, when I use the following code:

<?php
$objPHPExcel->getActiveSheet()->getStyle('A'.$sk)->getFill()->applyFromArray(
	array(
		'type'       => PHPExcel_Style_Fill::FILL_SOLID,
		'startcolor' => array('rgb' => 'E9E9E9'),
		'endcolor'   => array('rgb' => 'E9E9E9')
	)
);
?>

 Any suggestions solving this problem?

PS. As I looked over reference, the Apply from array has the required functions:

PHPExcel_Style

Array key:

Maps to property:

fill

font

borders

alignment

numberformat

protection

getFill()
getFont()
getBorders()
getAlignment()
getNumberFormat()
getProtection()

PHPExcel_Style_Fill

Array key:

Maps to property:

type
rotation
startcolor
endcolor

color

setFillType()
setRotation()
getStartColor()
getEndColor()
getStartColor()

 

But what corrent the source code should be for it.

Thanks!

Developer
Oct 20, 2009 at 2:18 AM

Starting with PHPExcel 1.7.0 the recommended way to style a range of cells is like this:

$objPHPExcel->getActiveSheet()->getStyle('A1:Z1')->getFill()->applyFromArray(
array(
'type' => PHPExcel_Style_Fill::FILL_SOLID,
'startcolor' => array('rgb' => 'E9E9E9'),
)
);

As you can see PHPExcel 1.7.0 has started to accept a cell range parameter for getStyle() method. The following metods are no longer recommended:

duplicateStyle()
duplicateStyleArray()
setSharedStyle()


All you need is getStyle() and applyFromArray().