首頁  >  問答  >  主體

PHPExcel 匯出 xls 亂碼

使用 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_leeringa_lee2683 天前720

全部回覆(2)我來回復

  • 習慣沉默

    習慣沉默2017-05-16 13:05:35

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

    回覆
    0
  • PHP中文网

    PHP中文网2017-05-16 13:05:35

    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');

    回覆
    0
  • 取消回覆