Note by: jon@webteaminc.com
This example will show how to merge cells and maintain the formatting. The basic idea is to format the cells and then apply the merge.
<code>
<?php
// Include PEAR::Spreadsheet_Excel_Writer
require_once "Spreadsheet/Excel/Writer.php";
// Create an instance
$xls =& new Spreadsheet_Excel_Writer();
// Send HTTP headers to tell the browser what's coming
$xls->send("test.xls");
$xls->setVersion(8);
// Add a worksheet to the file, returning an object to add data to
$sheet =& $xls->addWorksheet('Binary Count');
$sum=0;
// Create the format of the merged cells
// Using setAlign('center') works best (same as 'align' => 'center)
$format_a = array('bordercolor' => 'red',
'left' => 1,
'bottom' => 1,
'right' => 1,
'top' => 1,
'bold'=>'1',
'size' => '14',
'color'=>'green',
'align' => 'center');
// Add the format. This could be done all together.
// I keep it separated for ease of use
$format =& $xls->addFormat($format_a);
// Now apply the format to the cells you want to merge
// This is the same as:
// $sheet->write(1,0,'',$format);
// $sheet->write(1,1,'',$format);
// $sheet->write(1,2,'',$format);
// $sheet->write(1,3,'',$format);
// $sheet->write(1,4,'',$format);
// I just think it's cleaner
for($n=0; $n<=5; $n++) $sheet->write(1,$n,'',$format);
// Write in the title or whatever you want in the merged cells
$sheet->write(1,0,'My Sample Report',$format);
// Now apply the merge to the cells
$sheet->mergeCells(1,0,1,5);
/*
******************************************
* The rest of this just populates the sheet
* with some data and totals it up.
******************************************
*/
// Write some numbers
for ( $i=2;$i<15;$i++ ) {
// Use PHP's decbin() function to convert integer to binary
if($i == 1 ) {
$format =& $xls->addFormat(array('bold'=>'1',
'size' =>
'12',
'color'=>'red'));
$sheet->write($i,0,decbin($i), $format);
} else {
$sheet->write($i,0,decbin($i));
}
$sum = $sum + decbin($i);
}
$format_b = array('bordercolor' => 'blue',
'left' => 1,
'bottom' => 1,
'right' => 1,
'top' => 1,
'bold'=>'1',
'size' => '14',
'color'=>'green');
$format =& $xls->addFormat($format_b);
$sheet->write($i,0,$sum,$format);
$format_c = array('bordercolor' => 'blue',
'left' => 1,
'bottom' => 1,
'right' => 1,
'top' => 1,
'bold'=>'1',
'size' => '14',
'color'=>'green',
'align' => 'center'
);
$format =& $xls->addFormat($format_c);
$sheet->write($i,1,'TOTAL',$format);
// Finish the spreadsheet, dumping it to the browser
$xls->close();
?>
</code>