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

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

本文介绍了Excel无法打开由XLSXWriter创建的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用



当我运行我的test.php



我写错了什么?有人能帮我吗?
我坚持了好几个小时!

解决方案

与Fiddler。



你会发现你正在发送HTML < form ... 的XLSX内容,这当然不是一个有效的电子表格文件格式。



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

 <?php 
if(isset($ _ POST ['submit2'])&&($ _POST ['submit2'] =='Export'))
{//这是一个导出,发送文件
require_once('download.php');
退出; //不要在XLSX文件之后发送任何东西
} else {//不是导出,显示窗体
?>
< form action =test.phpmethod =post>
< input type =submitname =submit2value =Export/>
< / form>
<?php
}


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.

When I run my test.php

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

解决方案

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
}

这篇关于Excel无法打开由XLSXWriter创建的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-26 07:04