Zend2 Controller 中的 PHPExcel

标签 php zend-framework2 phpexcel

我正在尝试让 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/

相关文章:

php - 来自数据库的 Zend Framework 2 模块配置

javascript - PHPExcel 搜索/返回单元格中包含特定值的所有行

PHPExcel ERR_INVALID_RESPONSE 与 PHP7.0

php - 在 php 中读取 xls 日期

javascript - jQuery:循环注释 div 并获取字段值

php - 交响乐 : preg_match() expecting parameter

Php: sql 错误 "Error: Unknown column ' RM' in 'where clause' with query"

php - 同一页面上有两个ajax,但第二个没有得到第一个已更改的内容

zend-framework2 - 正确引导 Zend2 插件的方法是什么?

php - 更新记录时烦人的 DateTime 问题([dateStepNotStep] => 输入不是有效步骤)