php导出的Excel文件报错


导出的Excel文件无法打开,可以通过文本编辑软件打开,看有没有报错

<pre>An Error occurred while handling another error:
yii\web\HeadersAlreadySentException: Headers already sent in C:\dev\nginx\html\other\netmi-shop\shopping\vendor\phpoffice\phpexcel\Classes\PHPExcel\Writer\Excel2007.php on line 394. in C:\dev\nginx\html\other\netmi-shop\shopping\vendor\yiisoft\yii2\web\Response.php:366
Stack trace:
#0 C:\dev\nginx\html\other\netmi-shop\shopping\vendor\yiisoft\yii2\web\Response.php(339): yii\web\Response-&gt;sendHeaders()
#1 C:\dev\nginx\html\other\netmi-shop\shopping\vendor\yiisoft\yii2\web\ErrorHandler.php(135): yii\web\Response-&gt;send()
#2 C:\dev\nginx\html\other\netmi-shop\shopping\vendor\yiisoft\yii2\base\ErrorHandler.php(111): yii\web\ErrorHandler-&gt;renderException(Object(yii\web\HeadersAlreadySentException))
#3 [internal function]: yii\base\ErrorHandler-&gt;handleException(Object(yii\web\HeadersAlreadySentException))
#4 {main}
Previous exception:
yii\web\HeadersAlreadySentException: Headers already sent in C:\dev\nginx\html\other\netmi-shop\shopping\vendor\phpoffice\phpexcel\Classes\PHPExcel\Writer\Excel2007.php on line 394. in C:\dev\nginx\html\other\netmi-shop\shopping\vendor\yiisoft\yii2\web\Response.php:366
Stack trace:
#0 C:\dev\nginx\html\other\netmi-shop\shopping\vendor\yiisoft\yii2\web\Response.php(339): yii\web\Response-&gt;sendHeaders()
#1 C:\dev\nginx\html\other\netmi-shop\shopping\vendor\yiisoft\yii2\base\Application.php(392): yii\web\Response-&gt;send()
#2 C:\dev\nginx\html\other\netmi-shop\shopping\appserver\web\index.php(33): yii\base\Application-&gt;run()
#3 {main}</pre>

找到报错的原因,就好解决了,直接在输出文件流后,终止代码执行即可。

header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="ggdoc.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = \PHPExcel_IOFactory::createWriter($excel, 'Excel2007');
$objWriter->save('php://output');
exit();