PHP生成的Excel文件在下载时不同 [英] PHP generated Excel file is different when downloaded

查看:107
本文介绍了PHP生成的Excel文件在下载时不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个PHP文件,可以使用 http:// pear发现的模块生成xls文件。 php.net/package/Spreadsheet_Excel_Writer/

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

当我下载文件时,它包含大量垃圾数据Excel和OpenOffice。 diff表示那个/ tmp文件夹中的二进制文件和下载的文件是不同的。我猜测它与标题或fpassthru有关,但是调试问题没有太多的运气。

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.

有什么问题的想法是

推荐答案

在生成Excel文件的页面顶部添加以下代码

Add the following code at the top of the page where the excel file is generated

ob_clean();

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

This would clear all the gibberish data.Also check for any echo statements.If echo statements are present, remove them. The data should always present in format specified by excel package.

这篇关于PHP生成的Excel文件在下载时不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆