$workbook = new PHPExcel();
$workbook->createSheet()->setTitle('whatt')->setCellValue( 'A1', 'Another sheet' );
$workbook->createSheet()->setTitle('whatt')->setCellValue( 'A1', 'Another sheet' );
$objWriter = new PHPExcel_Writer_Excel2007($workbook);
$objWriter->setOffice2003Compatibility(true);
ob_start();
$objWriter->save( "php://output" );
$contents = ob_get_contents();
ob_end_clean();
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
$size = count($contents);
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false);
header('Content-Type: application/vnd.msexcel; charset=utf-8');
header("Content-Disposition: attachment; filename=\"test.xlsx\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: {$size}");
echo $contents;
exit;
When I download the sheet it comes down as 1 byte, with one sheet where the first cell is “P” ( because the file only contains that letter )
If I comment out the second createSheet line it works perfect. Any idea?
EDIT
I accepted the answer below which told me it wasn’t PHPExcel’s fault and it wasn’t.
If I remove the headers and keep output buffering, as a test, it still works.
ob_start();
$objWriter->save( "php://output" );
$contents = ob_get_contents();
ob_end_clean();
file_put_contents( "/mypath/uploads/test.xlsx", $contents );
I can download the file no problem. This leads me to believe the headers are screwing it up somehow, which is very bizarre considering there’s no issue if I only used createSheet once. I guess I’ll post that here when I figure it out.
….
And I figured out why the headers were messing it up. Apparently using count($contents) with one added sheet was fine, but with two added sheets it would only return 1. I changed it to strlen($contents) and it worked. Bonus points if anyone can tell me why that happened 🙂
No idea without a lot of debugging. Get rid of the redundant output buffering, and it works. This is the cause of your problem, nothing in PHPExcel.
So what are you doing subsequently with $contents?
Calling createSheet() twice in a row isn’t corrupting anything: though why are you trying to create a workbook containing two worksheets with the same title anyway? PHPExcel will actually rename the second added worksheet as whatt2 to avoid problems.