php_xlsxwriter - Excel cannot open file output from browser

963 views Asked by At

Using PHP_XLSXWriter, if I write an .xlsx file to the server, download and then open it in Excel all works well :-

include_once("xlsxwriter.class.php");
$filename = "example.xlsx";
$rows = array(
    array('year','month','amount'),
    array('2003','1','220'),
    array('2003','2','153.5'),
);

$writer = new XLSXWriter();
$writer->writeSheet($rows);
$writer->writeToFile("/path/to/file/$filename");

However if I output the file direct from the browser, opening the downloded file gives me the error message "Excel cannot open the file 'example.xlsx' because the file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

include_once("xlsxwriter.class.php");
$filename = "example.xlsx";
header('Content-disposition: attachment; filename="'.XLSXWriter::sanitize_filename($filename).'"');
header("Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
header('Content-Transfer-Encoding: base64');
header('Cache-Control: must-revalidate');
header('Pragma: public'); 

$rows = array(
    array('year','month','amount'),
    array('2003','1','220'),
    array('2003','2','153.5'),
);

$writer = new XLSXWriter();
$writer->writeSheet($rows);
$writer->writeToStdOut();

This is running on a Ubuntu 20 server running Apache2 and PHP 7.2

Any ideas what is going wrong?

Many thanks

1

There are 1 answers

0
Jules On

I found the problem....I had a single space outside the tags in the xlsxwriter.class.php file. Infuriating.