PHPExcel 匯出 xls 亂碼
ringa_lee
ringa_lee 2017-05-16 13:03:35
0
2
716

使用 PHPExcel 的 save 方法時,

// 保存为 xls 文件,但是这个只是保存到服务器上了,还需要手动下载到本地
$writer->save('商品列表.xls');

直接下載:

        if ($this->fileVersion == 'Excel5') {
            header('Content-Type: application/vnd.ms-excel');   // 输出xls格式的文件
            header('Content-Disposition: attachment;filename="' . $config['fileName'] . '.xls"'); //告诉浏览器输出文件的名称
        } else {
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');  // 输出xlsx格式的文件
            header('Content-Disposition: attachment;filename="' . $config['fileName'] . '.xlsx"'); //告诉浏览器输出文件的名称
        }

        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $writer->save('php://output');

透過php://output 可以直接下載導出的xls 文件,並且不會在伺服器上產生xls 文件;
但是,在下載的時候,直接報錯,這個錯誤是在瀏覽器開發者工具中的network 中出現的,也沒有觸發文件下載操作

一直沒查到這個亂碼是怎樣造成的,如果直接在 header 之前,print_r($writer); exit; 看到的物件 $writer 是沒有亂碼的

很困惑這個問題

ringa_lee
ringa_lee

ringa_lee

全部回覆(2)
習慣沉默

問題已解決,這種方式可以直接下載導出的文件,但是不能使用 Ajax

Ty80

header('Content-Type: application/vnd.ms-excel');改为header('Content-Type: application/vnd.ms-excel; charset=UTF-8');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');改为header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8');

熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!