Unable to save the Excel file correctly (using Yii Framework)

Topics: Developer Forum, User Forum
Mar 11, 2013 at 9:29 AM
Hi there,

I'm REALLY stuck with something that shouldn't be that complicated... I'm using the Yii Framework and trying to export a Excel file containing data from a database. The only method that actually generates a correct Excel file with the expected data involves saving the file automatically, which saves it in the directory where the PHP file is stored, which is the server. As I want this file to be saved for the client where they want to, I want to show a kind of "open/save as" dialog... Yes, I've already read like 20 threads about it, but none of them seems to solve my case...

I've tried basically two different approaches: The first one, which saves the correct Excel file to the server directory, is this one:

[code]
...
$objPHPExcel = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save(str_replace('.php', '.xlsx', FILE));
[\code]

This method saves an excel file called like the PHP file (changing the extension) that actually works fine, but it is automatically saved in the same directory where the PHP file is without even notifying it (nor letting the user select where to save it).

Following some existing threads on this topic, I've tried a second approach:

[code]
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="my-file.xlsx"');
header('Cache-Control: max-age=0');

$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
$objWriter->save('php://output');
[\code]

This method saves the file automatically to the default download folder, but saves a kind of messy excel document containing the header of the page, plenty of strange, chinese characters, every echo contained in the page and other weird things that would make anyone cry.

Any idea of what to do? I'm working within the Yii Framework, so I understand that the default header included in the page can be giving me some trouble, though I don't understand why the first way generates a correct file but the second do not... However, I can't use an "external" PHP (I mean not "included" within the Yii-generated pages) because i get a forbidden access error...

Some has some clues about this?

Thanks in advance!
Mar 12, 2013 at 9:58 AM
Finally I've been able to kind-of solve it... If anyone ever encounters the same problem that I've been facing, check out this Yii Extension (which is, in fact, an extension of an extension that extends PhpExcel): http://www.yiiframework.com/extension/yiireport/