【问题标题】:Download Excel From Server Using PHP使用 PHP 从服务器下载 Excel
【发布时间】:2013-06-07 07:56:06
【问题描述】:

谁能帮我在 PHP 上编写代码以从服务器下载 Excel 文件。

我使用headerreadfile 创建了以下代码,但下载的文件已损坏。

//content type
header('Content-type: application/vnd.ms-excel');
//open/save dialog box
header('Content-Disposition: attachment; filename='.$fileName);
//read from server and write to buffer
readfile($reportPath);

谁能帮助我从服务器下载现有 Excel 文件的最佳方式。

下载后请看下图

【问题讨论】:

  • 那么你实际上是如何创建这个文件的?
  • 我正在使用 PHPExcel 创建这个文件。但错误出现在下载部分。因为我也测试过打开一个excel然后有一些数据然后保存并上传到服务器。但下载时输出文件仍然出错..

标签: php excel header download


【解决方案1】:
ob_clean();

将该代码放在所有标头声明之前

【讨论】:

    【解决方案2】:

    我建议使用 X-SENDFILE 标头。 https://tn123.org/mod_xsendfile/

    【讨论】:

    • 服务器配置有什么要添加到使用的 X-SendFILE 的吗??
    • 您必须启用该模块。您还必须将虚拟主机配置为要服务的文件。在 php 中你只需要设置一个标题。
    【解决方案3】:

    我使用类似以下的东西:

    header("Content-Description: File Transfer");
    header("Content-Type: application/octet-stream");
    header('Content-Disposition: attachment; filename="'.basename($path).'"');
    header("Content-Transfer-Encoding: binary");
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header("Content-Type: application/force-download");
    header("Content-Type: application/download");
    header("Content-Length: ".filesize($path));
    readfile($path);
    exit;
    

    确保您没有在读取文件之前或之后输出任何内容。

    【讨论】:

    • 很遗憾但打开下载的excel文件时仍然出现同样的错误
    • 尝试使用 txt 文件,看看它是如何下载的。它的原始内容是否完好无损?
    • 我已经尝试过txt文件,内容是原样..但是为什么excel无法获取实际内容?
    • 一个常见的情况是输出中存在一个不可见的、不可打印的字符预设与您的文件混淆(尤其是如果您不使用英语)。如果你打开错误报告,你会得到什么吗?把它放在你的第一个 header() 上面:error_reporting(E_ALL);ini_set('display_errors', true);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-02
    • 2017-10-18
    相关资源
    最近更新 更多