如何在symfony2中使用PHPExcel修改excel文件

时间:2012-12-02 19:23:54

标签: php symfony phpexcel

在我的项目中,我使用symfony2 PHPExcel包装器https://github.com/liuggio/ExcelBundle

通过上面链接的示例,我可以创建新的Excel文件。但是这个文件根本没有样式或标记。所以我创建了一个excel模板,我想输入一些数据。

我知道如何加载excel文件:

$excelObj = $this->get('xls.load_xls2007')
                 ->load($this->get('kernel')
                 ->getRootDir() . '/../web/excel-template.xlsx');

//custom modifications on excel file

现在我需要创建一个响应。但是在ExcelBundle的文档中没有关于如何做到这一点的信息。它们只显示响应如何适用于由代码创建的excel文件。

我试过了:

 $excelService->setExcelObj($excelObj);
 $response = $excelService->getResponse();
 //the rest is equal to the code in the doc

但它给了我一个空白的Excel文档。

如何使用加载的Excel文件进​​行响应?

3 个答案:

答案 0 :(得分:1)

你可以通过

来做到这一点
// Read the file
    $objReader = PHPExcel_IOFactory::createReader($fileType);
    $objPHPExcel = $objReader->load($fileName);

    // Change the file
    $objPHPExcel->setActiveSheetIndex(0)
                ->setCellValue('A1', 'Hello')
                ->setCellValue('B1', 'World!');

    // Write the file
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $fileType);
    $objWriter->save($fileName);

如果您不明白请发表评论..

答案 1 :(得分:0)

我会将文件保存到磁盘并将用户个人重定向到磁盘版本。这将允许几件事

  • 您的Web服务器提供文件而不是PHP,从性能和内存使用角度来看,这是一件好事。
  • 将您的体系结构稍微拆分以允许将来的更改,例如将创建和加载Excel文件移动到异步操作。
  • 使用http://wiki.nginx.org/XSendfile的能力(还有一个Apache模块)。
  • 用户可以重新下载文件或暂停和恢复下载而无需重新创建。

要执行此操作,您需要

  • 在创建
  • 后将文件保存到Web可访问的临时目录中
  • 将用户重定向到该文件位置
  • 创建一个删除临时目录中旧文件的cron或其他作业。

tempfile api(http://us2.php.net/tmpfile)在这里可能很有用。

答案 2 :(得分:0)

PHPExcelbundle的新版本2. *可以帮助你。

现在可以:

//read
$phpExcelObject = $this->get('phpexcel')->createPHPExcelObject('file.xls');
$phpExcelObject->setActiveSheetIndex(0)
  ->setCellValue( 'C6', 'some text' )
  ->setCellValue( 'D6', 'some text2' );
$writer = $this->get('phpexcel')->createWriter($phpExcelObject, 'Excel5');
$writer->save('file.xls');
// or 
$response = $this->get('phpexcel')->createStreamedResponse($writer);