PHPExcel & Kohana
Either write something worth reading or do something worth writing. – Benjamin Franklin
I am so glad that there are people out there who write all this wonderful code. I wanted to export a table as an excel file so did a quick search and found PHPExcel.
So many people have written great documentation about getting started with PHPExcel and I don’t want to duplicate those.
For instance:
PHPExcel : Advanced Read-Write Excel Made Simple
Hello World spreadsheet with PHPExcel
kohana 3.2 tutorial
I would, however, like to briefly document what I had to do to get it all working under Kohana 3.3
Step 1:
I extracted the current release of PHPExcel (1.8.0) to applicationvendorPHPExcel1.8.0
Step 2:
I added
'vendor' => APPPATH.'vendor'
to the Kohana::modules section of my bootstrap file so that Kohana would know where to look for vendor specific files
Step 3:
I created a new action in one of my controllers that would export an Excel file.
public function action_excel()
{
require_once Kohana::find_file('PHPExcel/1.8.0', 'Classes/PHPExcel');
$objPHPExcel = new PHPExcel();
/* lots of setting up data... look elsewhere for how to do this */
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('output.xls');
}
So Far:
This worked perfectly but it saved output.xls to the root directory of the web site on the server.
Step 4:
Send file to output stream
public function action_excel()
{
require_once Kohana::find_file('PHPExcel/1.8.0', 'Classes/PHPExcel');
$objPHPExcel = new PHPExcel();
/* lots of setting up data... look elsewhere for how to do this */
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="output.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
}
Conclusion:
This couldn’t be easier. Truly. And the documentation and examples are awesome.
