Change font style in PHPExcel

October 05, 2013 | 10594 views | Comments

Stylize fonts in PHPExcel, change font color, font face, font-weight, and font size.

For example.

Prepare the new style in an array before applying in a given cell.

//set up the style in an array
$style = array('font' => array('size' => 10,'bold' => true,'color' => array('rgb' => 'ff0000')));

//apply the style on column A row 1 to Column B row 1
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->applyFromArray($style);

// add some text
$objPHPExcel->getActiveSheet()->setCellValue('A1','The');
$objPHPExcel->getActiveSheet()->setCellValue('B1','quick');
$objPHPExcel->getActiveSheet()->setCellValue('A2','brown');
$objPHPExcel->getActiveSheet()->setCellValue('C1','fox');

Result.

Please mouse over here to view the image.

 

Directly apply the new style in the function.

//apply the style on column A row 1 to Column B row 1
$objPHPExcel->getActiveSheet()->getStyle('A1:B1')->applyFromArray(array('font' => array('size' => 10,'bold' => true,'color' => array('rgb' => '000000'))));

// add some text
$objPHPExcel->getActiveSheet()->setCellValue('A1','The');
$objPHPExcel->getActiveSheet()->setCellValue('B1','quick');
$objPHPExcel->getActiveSheet()->setCellValue('A2','brown');
$objPHPExcel->getActiveSheet()->setCellValue('C1','fox');

Result.

Please mouse over here to view the image.

 

Apply specific font styles to multiple cells.

//apply different font styles to different cells
$objPHPExcel->getActiveSheet()->getStyle('A1:A1')->applyFromArray(array('font' => array('size' => 18,'bold' => true,'color' => array('rgb' => '0000ff'))));
$objPHPExcel->getActiveSheet()->getStyle('B1:B1')->applyFromArray(array('font' => array('size' => 14,'bold' => true,'color' => array('rgb' => 'ff0000'))));
$objPHPExcel->getActiveSheet()->getStyle('C1:C1')->applyFromArray(array('font' => array('size' => 9,'bold' => true,'color' => array('rgb' => '00ff00'))));
$objPHPExcel->getActiveSheet()->getStyle('A2:A2')->applyFromArray(array('font' => array('size' => 24,'bold' => true,'color' => array('rgb' => 'eeeeee'))));

// add some text
$objPHPExcel->getActiveSheet()->setCellValue('A1','The');
$objPHPExcel->getActiveSheet()->setCellValue('B1','quick');
$objPHPExcel->getActiveSheet()->setCellValue('A2','brown');
$objPHPExcel->getActiveSheet()->setCellValue('C1','fox');

Result.

Please mouse over here to view the image.