在Symfony中使用liuggio / ExcelBundle清空PHPExcel文件

我有一些代码遍历Excel工作表的行和列,并用其他文本replace文本。 这是由具有excel文件和字典作为参数的服务完成的。

$mappedTemplate = $this->get('app.entity.translate')->translate($phpExcelObject, $dictionary); 

服务本身看起来像这样。

 public function translate($template, $dictionary) { foreach ($template->getWorksheetIterator() as $worksheet) { foreach ($worksheet->getRowIterator() as $row) { $cellIterator = $row->getCellIterator(); $cellIterator->setIterateOnlyExistingCells(false); // Loop all cells, even if it is not set foreach ($cellIterator as $cell) { if (!is_null($cell)) { if (!is_null($cell->getCalculatedValue())) { if (array_key_exists((string)$cell->getCalculatedValue(), $dictionary)) { $worksheet->setCellValue( $cell->getCoordinate(), $dictionary[$cell->getCalculatedValue()] ); } } } } } } return $template; } 

经过一些debugging后,我发现文本实际上被replace了,而且服务的工作方式应该是这样。 问题是,当我返回新的PHPExcel文件作为响应下载时,Excel是空的。

这是我用来返回文件的代码。

 // create the writer $writer = $this->get('phpexcel')->createWriter($mappedTemplate, 'Excel5'); // create the response $response = $this->get('phpexcel')->createStreamedResponse($writer); // adding headers $dispositionHeader = $response->headers->makeDisposition( ResponseHeaderBag::DISPOSITION_ATTACHMENT, $file_name ); $response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'); $response->headers->set('Pragma', 'public'); $response->headers->set('Cache-Control', 'maxage=1'); $response->headers->set('Content-Disposition', $dispositionHeader); return $response; 

我错过了什么?

您的代码缺less对作者的调用。

您只能创build编写器,但不要使用它,至less不要在您的共享代码示例中使用它:

 $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); $response = $this->get('phpexcel')->createStreamedResponse($objWriter) 

另一件事是内容types:你有正确的Apache内容types设置?

 $response->headers->set('Content-Type', 'application/vnd.ms-excel; charset=utf-8'); 
Interesting Posts