问题
In my project I use symfony2 PHPExcel wrapper https://github.com/liuggio/ExcelBundle
With the example from the link above I can create new excel files. However this file has no style or markup at all. So I created a excel template where I want to input some data.
I know how to load an excel file:
$excelObj = $this->get('xls.load_xls2007')
->load($this->get('kernel')
->getRootDir() . '/../web/excel-template.xlsx');
//custom modifications on excel file
Now I need to create a response. But in the doc of ExcelBundle there is no information on how to do that. They just show how response work for a excel file that is created by code.
I tried:
$excelService->setExcelObj($excelObj);
$response = $excelService->getResponse();
//the rest is equal to the code in the doc
but it gives me a blank excel document.
Any ideas how to make a response with a loaded excel file?
回答1:
you can do this by
// 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);
if you dont understand please comment..
回答2:
I would save the file to disk and redirect the user to the on-disk version personally. This will allow several things
- Your web server to serve files instead of PHP, a good thing from a performance and memory usage standpoint.
- Decouple your architecture a bit to allow for future changes such as moving the creation and loading of Excel files to asynchronous operations.
- The ability to use http://wiki.nginx.org/XSendfile (There is an Apache module also).
- The user can re-download the file or pause and resume download without recreating it.
To do this you will want to
- Save the file to a web accessible temp directory after its created
- Redirect the user to that file location
- Create a cron or some other job that deletes older files in the temp directory.
The tempfile api (http://us2.php.net/tmpfile) might be useful here.
回答3:
the new version 2.* of PHPExcelbundle could help you.
Is now possible:
//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);
来源:https://stackoverflow.com/questions/13672851/how-to-modify-excel-file-using-phpexcel-in-symfony2