3

I have a PHP file that generates xls files using the module found at http://pear.php.net/package/Spreadsheet_Excel_Writer/

I can create the sample document just fine and when I open it, it looks fine.

My next step it to turn it into a downloadable link. To do that, I did this:

    $mimeType = "application/vnd.ms-excel";
    $file_name = "test.xls";
    $file_path = "/tmp/".$file_name;
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header('Content-Type: application/' . $mimeType);
    header('Content-Length: '.$size);
    header("Content-Disposition: attachment;filename=$file_name ");
    header("Content-Transfer-Encoding: binary ");

    // open the file in binary read-only mode
    // display the error messages if the file can´t be opened
    $file = & fopen($file_path, 'rb');

    if ($file) {
        // stream the file and exit the script when complete
        fpassthru($file);
        exit;

    } else {
        echo $err;
    }

When I download the file however, it contains a lot of garbage data both in Excel and OpenOffice. The diff says that then binary file in the /tmp folder and the downloaded file are different from each other. I'm guessing that it has something to do with the headers or with fpassthru but I haven't had much luck with debugging the issue.

Any ideas on what the problem is?

4

4 回答 4

0

多个 Content-Type 标头是不必要的。您实际上是在说文件是松饼、比萨饼和福特金牛座。您只需要application/octet-stream版本,除非您想提供确切的 mime 类型。

同样,您是否有任何理由试图将返回的文件句柄fopen()转换为引用?

尝试更简单的方法:

<?php

header("Content-Type: application/octet-stream");
header("Content-Disposition: attachment;filename=$file_name");

readfile("/tmp/test.xls");

exit();
?>

看看是否有更好的效果。

于 2010-09-13T22:40:27.743 回答
0

只需确保在发送实际文件内容之前不向浏览器发送任何内容。

可能只是Spreadsheet_Excel_Writer 正在生成的一些php“错误”甚至“通知”,而您甚至都看不到。或者它可能是一个结束的 '?>' 标记,后面跟着一个简单的空格或换行符。

在 Web 文件夹中生成的文件正常工作时,我遇到了类似的错误。但是使用 header('...') 的传递给了我损坏的文件。这是由于一个 php 文件末尾的一个空格在关闭 '?>' 标记之后造成的。

于 2013-06-11T15:41:23.200 回答
0

我正在使用同一个库,我刚刚发现库本身中的文件正在创建空白。

解决方案:在以下文件中删除文件末尾的空格,或删除末尾的?>结束标记。

要编辑的文件( 中的所有文件Spreadsheet_Excel_Writer package):

Writer.php 
Workbook.php
Worksheet.php
PPS.php
Parser.php
OLE.php
Parser.php
File.php
BIFFWriter.php
Validator.php
Root.php
于 2015-07-09T11:26:08.170 回答
0

在生成excel文件的页面顶部添加如下代码

ob_clean();

这将清除所有乱码数据。还要检查任何回声语句。如果存在回声语句,请将它们删除。数据应始终以 excel 包指定的格式显示。

于 2016-08-05T12:26:00.893 回答