我正在使用Zend上的PHPExcel创建包含UTF-8编码数据的Excel报告。当我下载并尝试在Excel中打开它时,它适用于本地环境但我收到以下错误:来自live sever / production的“不正确的文件格式”。任何帮助/参考将不胜感激。
这是我用来下载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;
}
答案 0 :(得分:0)
您必须在保存之前使用此行:
ob_end_clean();