本人使用过很多次phpexcel了,有时需要保存文件到磁盘,有时需要浏览器弹出下载。保存到磁盘一半不会出现问题,关键是浏览器弹出保存,经常会发生导出的excel文件无法打开,提示文件格式或文件名无效,文件损毁。在此,记录一下解决办法。
1、xls还是xlsx?首先确定导出的excel文件扩展名
2、添加header,不同的文件类型,不同的header。 我就是这里出了问题,xlsx用了xls的header,导致导出的excel无法打开。
2007excel:xlsx如下:
$excelName = '绩效得分统计'.time();
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$excelName.'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
exit;
2003excel:xls如下:
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="links_out'.$timestamp.'.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
例如xlsx,完整参考如下:
//非常重要(放到header();前)
ob_end_clean();//解决excel无法打开问题的函数
header('Content-Type: application/vnd.ms-excel');//设置下载前的头信息\
header('Content-Disposition: attachment;filename="商品订单1.xlsx"');\
header('Cache-Control: max-age=0');\
$phpwriter=new \PHPExcel_Writer_Excel2007($phpexcel);//此处的2007代表的是高版本的excel表格\
$phpwriter->save('php://output');//生成并下载excel表格