Excel 无法打开由 XLSXWriter 创建的文件

Excel cannot open the file created by XLSXWriter

我正在使用 https://github.com/mk-j/PHP_XLSXWriter 库。

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();
?>

我单独运行download.php的时候就可以了

当我 运行 我的 test.php

我写错了什么?有人能帮我吗?
我在这上面卡了好几个小时!

检查您的 HTTP 响应,例如使用 Fiddler。

您会发现您发送的是 XLSX 内容前面的 HTML <form...,这当然不是有效的电子表格文件格式。

在您的 writeToStdOut() 调用之前必须 没有 输出 - 例如,您的文件应该如下所示:

<?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
}