1

我正在使用 Zend 上的 PHPExcel 创建一个包含 UTF-8 编码数据的 Excel 报告。当我下载并尝试在 Excel 中打开它时,它可以在本地环境中运行,但我收到以下错误:来自实时服务器/生产的“文件格式不正确”。任何帮助/参考将不胜感激。

这是我用来下载 xls 文件的代码:

public function getCsv($data, $filename = false)
 {
     /**
      * generate a file name using unixTimeStamp
      * @var string $tmpfname
      */
      if ($filename)
      {
          $tmpfile =    "/tmp/".$filename. "-". date('Y-m-d_H:i:s') . ".csv";
          $name = str_replace(' ','',$filename)."-".date('Y-m-d_H:i:s') . ".xls";
      }
      else
      {
          $tmpfile = "/tmp/report". "_". date('Y-m-d_H:i:s') . ".csv";
          $name = "report-".date('Y-m-d_H:i:s') . ".xls";
      }
      /**
       * open Temporary file name in write mode
       * @var object $fp
       */
       $fp = fopen($tmpfile, "w");
       /**
        * foreach datas write to csv
        */
       foreach ($data as $fields)
           fputcsv($fp, $fields, ',', '"');

       /**
        * close file
        */
        fclose($fp);

        try
        {
            $objReader = PHPExcel_IOFactory::createReader('CSV');
            $objPHPExcel = $objReader->load($tmpfile);
            $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

            //set Header Content Type as application/csv
            header("Content-Type: application/vnd.ms-excel; charset=utf-8");
            header("Content-Disposition: attachment; filename=$name");
            $objWriter->save('php://output');
        }
        catch (Exception $e)
        {
            echo $e->getMessage();
        }

        exit;
    }
4

1 回答 1

0

您必须在保存之前使用此行:

ob_end_clean();
于 2014-02-19T16:11:20.480 回答