KKL Michael KKL Michael - 3 months ago 20
HTML Question

Excel cannot open the file created by XLSXWriter

I am using https://github.com/mk-j/PHP_XLSXWriter library.

test.php

<form action="test.php" method="post">
<input type="submit" name="submit2" value="Export" />
</form>

<?php
if(isset($_POST['submit2']) && ($_POST['submit2'] == 'Export'))
{
include_once('download.php');
}
?>


download.php (https://github.com/mk-j/PHP_XLSXWriter/blob/master/example.php)

<?php
include('./PHP_XLSXWriter-master/xlsxwriter.class.php');

ini_set('display_errors', 0);
ini_set('log_errors', 1);
error_reporting(E_ALL & ~E_NOTICE);

$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: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');

$header = array(
'year'=>'string',
'month'=>'string',
'amount'=>'money',
'first_event'=>'datetime',
'second_event'=>'date',
);

$data1 = array(
array('2003','1','-50.5','2010-01-01 23:00:00','2012-12-31 23:00:00'),
array('2003','=B2', '23.5','2010-01-01 00:00:00','2012-12-31 00:00:00'),
);

$data2 = array(
array('2003','01','343.12'),
array('2003','02','345.12'),
);

$writer = new XLSXWriter();
$writer->setAuthor('Some Author');
$writer->writeSheet($data1,'Sheet1',$header);
?>
$writer->writeSheet($data2,'Sheet2');
$writer->writeToStdOut();
?>


When I seperately run download.php, it is OK.

enter image description here

When I run my test.php

enter image description here

What am I writing wrong? Can someone help me?
I am stuck on this for many hours!

Answer

Check your HTTP responses e.g. with Fiddler.

You'll find that you're sending the HTML <form... in front of the XLSX content, which is - of course - not a valid spreadsheet file format.

There must be no output at all before your writeToStdOut() call - for example, your file should look something like this:

<?php
if(isset($_POST['submit2']) && ($_POST['submit2'] == 'Export'))
{ // this is an export, send the file
    require_once('download.php');
    exit; // do not send anything else after the XLSX file
} else { // not an export, show the form
    ?>
    <form action="test.php" method="post">
        <input type="submit" name="submit2" value="Export" />
    </form>
    <?php
}