Creating Multiple Worksheet Excel Exports with PHPExcel [www.phpexcel.net]

Recently I needed to build and Excel file from a web application. The most common solution is to generate a CSV or TSV file, which can then be imported into Excel. In my case, the client wanted multiple worksheets, so I searched and found PHPExcel. This library provides simple tools to build OpenXML files. There are also libraries for Word and Powerpoint.
Here is how I solved the problem:
$objPHPExcel = new PHPExcel();
$sheet_count = 0;
foreach ($courses as $c) {if ($sheet_count > 0) {
// This creates the next sheet in the sequence
// One sheet per "course" in this example
$objPHPExcel->createSheet();
$objPHPExcel->setActiveSheetIndex($sheet_count);
}
// Add tab label to the sheet
$objPHPExcel->getActiveSheet()->setTitle(substr($c->name,0,30));
// Sheet heading in the first row
$objPHPExcel->getActiveSheet()->setCellValue('A1',$c->name);
// Column headings in the second row
$objPHPExcel->getActiveSheet()->setCellValue('C2','Email');
$objPHPExcel->getActiveSheet()->setCellValue('D2','Last Name');
$objPHPExcel->getActiveSheet()->setCellValue('E2','First Name');
$objPHPExcel->getActiveSheet()->setCellValue('F2','Middle');
$objPHPExcel->getActiveSheet()->setCellValue('G2','Suffix');
$row = 2;
$members = $c->getMembers(999999);
foreach ($members as $m) {
$row++;
$first_last = split(' ',$m->name);
$objPHPExcel->getActiveSheet()->setCellValue('C'.$row,$m->email);
$objPHPExcel->getActiveSheet()->setCellValue('D'.$row,$first_last[0\
]);
$objPHPExcel->getActiveSheet()->setCellValue('E'.$row,$first_last[1\
]);
$objPHPExcel->getActiveSheet()->setCellValue('F'.$row ,""); // midd\
le
$objPHPExcel->getActiveSheet()->setCellValue('G'.$row ,""); // suff\
ix
}
$sheet_count++;
}
// Redirect output to a client’s web browser
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheet\
ml.sheet');
header('Content-Disposition: attachment;filename="MEMBERS.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
Subscribe to notificaitons