PHPExcel in Zend2 Controller

余生颓废 提交于 2019-12-06 08:19:43

As @Aydin Hassan commented, I've tried with:

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
ob_start();
$objWriter->save('php://output');
$excelOutput = ob_get_clean();

And then simply passed $excelOutput to the response content, and it works simply great!

$response->setContent($excelOutput);

So you can archive, in your controller action, something like this:

 public function testPHPExcelAction() {
    // I recommend constructor injection for all needed dependencies ;-)
    $this->phpExcelService = $this->serviceLocator->get('mvlabs.phpexcel.service');

    $objPHPExcel = $this->phpExcelService->createPHPExcelObject();
    $objPHPExcel->getProperties()->setCreator("Diego Drigani")
        ->setLastModifiedBy("Diego Drigani")
        ->setTitle("MvlabsPHPExcel Test Document")
        ->setSubject("MvlabsPHPExcel Test Document")
        ->setDescription("Test document for MvlabsPHPExcel, generated using Zend Framework 2 and PHPExcel.")
        ->setKeywords("office PHPExcel php zf2 mvlabs")
        ->setCategory("Test result file");
    $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A1', 'Hello')
        ->setCellValue('B2', 'world!')
        ->setCellValue('C1', 'Hello')
        ->setCellValue('D2', 'world!');
    $objPHPExcel->setActiveSheetIndex(0)
        ->setCellValue('A4', 'Miscellaneous glyphs')
        ->setCellValue('A5', 'éàèùâêîôûëïüÿäöüç');

    $objPHPExcel->getActiveSheet()->setCellValue('A8',"Hello\nWorld");
    $objPHPExcel->getActiveSheet()->getRowDimension(8)->setRowHeight(-1);
    $objPHPExcel->getActiveSheet()->getStyle('A8')->getAlignment()->setWrapText(true);
    $objPHPExcel->getActiveSheet()->setTitle('Mvlabs');
    $objPHPExcel->setActiveSheetIndex(0);

    $objWriter = $this->phpExcelService->createWriter($objPHPExcel, 'Excel2007' );

    $response = $this->phpExcelService->createHttpResponse($objWriter, 200, [
        'Pragma' => 'public',
        'Cache-control' => 'must-revalidate, post-check=0, pre-check=0',
        'Cache-control' => 'private',
        'Expires' => '0000-00-00',
        'Content-Type' => 'application/vnd.ms-excel; charset=utf-8',
        'Content-Disposition' => 'attachment; filename=' . 'myTest.xls',
        ]);

    return $response;

}    

To do it in the above way, you need to use the MvlabsPHPExcel module that gives to you the possibility to use PHPOffice/PHPExcel library into a ZF2 application easily.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!