After building my spreadsheet using PHPExcel, I am unable to open the “save as” or “open” dialog. I got the following code snippet right from the examples directory that comes with the PHPExcel library.
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="01simple.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
My JavaScript:
$(document).on('submit', '#myForm', function(e) {
$.post('mail.php', $(this).serialize(), function (data) {
$('.signature-field,.notes').hide();
//SUCCESS
$('.successORfail').html(data);
setTimeout(function(){
$(".successORfail").fadeOut("slow", function () {
$(".successORfail").empty().show();
});
}, 4500);
}).error(function() {
alert("Fatal Error: mail.php not found!");
});
e.preventDefault();
});
Note: the code above generates the alert message “Fatal Error: mail.php not found!” that I set up. Other than that, it does not generate any error messages, it does not save or create an excel file.
When I use the following method, without any headers, the excel file is created perfectly, and saves on the server, without any errors:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('MyExcel.xlsx');
I would truly appreciate any help with troubleshooting this error, as I have been working on this for a very long time now.
Many thanks in advance!
You actually cannot do this the way you are attempting to do this. Javascript by itself cannot initiate a file download on the user’s system (due to security issues). I am aware of at least one jQuery plugin which gives an AJAX-like download experience. You might check this out:
http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx