我正在尝试让 PHPExcel 与 Zend2 一起使用。实际上它正在工作,但不符合我的预期(我可以写入文件,但不能在不保存的情况下下载)。我找到了一些例子,你只需做这样的事情:
$objPHPExcel = ....
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="01simple.xls"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
并且文件被允许下载。如何在 Zend2 Controller 中实现类似的功能?到目前为止我已经尝试过:
public function generateRaportAction()
{
$objPHPExcel = new PHPExcel();
$objPHPExcel->getActiveSheet()->setCellValue( 'B8', 'Some value' );
$objWriter = \PHPExcel_IOFactory::createWriter( $objPHPExcel, 'Excel5' );
$response = $this->getEvent()->getResponse();
$response->getHeaders()->clearHeaders()->addHeaders( array(
'Pragma' => 'public',
'Content-Type' => 'application/vnd.ms-excel',
'Content-Disposition' => 'attachment; filename="test.xls"',
'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
'Content-Transfer-Encoding' => 'binary',
) );
$objWriter->save( 'php://output' );
return $response;
}
但它在我的页面上给了我“类似 echo ”的输出。我的第二次尝试是:
$response->setContent($objWriter->save( 'php://output' ));
但结果是一样的。
最佳答案
正如 @Aydin Hassan 评论的那样,我尝试过:
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_start();
$objWriter->save('php://output');
$excelOutput = ob_get_clean();
然后只需将 $excelOutput
传递给响应内容,效果非常好!
$response->setContent($excelOutput);
关于Zend2 Controller 中的 PHPExcel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16551375/