0

我想用 php 读取一个 excel 文件并将其内容发送到客户端。我真正想做的是通过更改内容类型和其他 html 标头强制浏览器下载文件而不是显示其内容。一切正常,用户可以下载文件,但是当他试图打开它时,内容没有以正确的格式和形状显示。我想到的事情是我不应该以 unicode 字符串发送响应,而必须以 excel 可以知道的二进制格式发送响应。这是我当前的代码:

$filename = $_GET['file'];
        $ext = $_GET['type'];
        $filename .= '.' . $ext;
        $path = "../generatedReports/" . $filename;
        header('Content-type: application/vnd.ms-excel;');
        header('Content-Disposition: attachment; filename=' . $filename);
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public", false);
        header("Content-Description: File Transfer");
        header("Accept-Ranges: bytes");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: " . filesize($path));
        $size = filesize($path);
        $f = fopen($path, 'r');
        $content = fread($f, $size);
        echo $content;

有什么解决办法吗?

4

2 回答 2

0

请尝试使用以下代码,

echo unicode2utf8(hexdec("00CE")); // Result: Î

// Or the function that will recognize U+ in front of string, and will skip it to show the character
function unicodeCodePointToChar($str) {
    if (substr($str,0,2) != "U+") return $str;
    $str = substr($str,2); // Skip U+
    return unicode_to_utf8(array(hexdec($str)));
}
echo unicodeCodePointToChar("U+00CE"); // Result: Î
于 2013-02-06T05:39:09.187 回答
0

这个答案解决了我的问题。我已将代码更改为:

$filename = $_GET['file'];
            $ext = $_GET['type'];
            $filename .= '.' . $ext;
            $path = "../generatedReports/" . $filename;
            header('Content-type: application/vnd.ms-excel;');
            header('Content-Disposition: attachment; filename=' . $filename);
            header("Pragma: public");
            header("Expires: 0");
            header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
            header("Cache-Control: public", false);
            header("Content-Description: File Transfer");
            header("Accept-Ranges: bytes");
            header("Content-Transfer-Encoding: binary");
            ob_clean();   // discard any data in the output buffer (if possible)
            flush();      // flush headers (if pos
            readfile($path);

一切都变得美好。

于 2013-02-06T13:03:40.277 回答