How do I write my excel spreadsheet into a variabl

2020-02-08 13:54发布

问题:

After loading a PHPExcel object with my data, I want to output the contents directly into a php variable, instead of writing to a file. Have I missed the method to do that, for it seems that the only way to save is to save to disk.

回答1:

You can use a writer to save to disk, or save to php://output. If the latter, you could use output buffering to capture that output and then store in a variable.... not sure quite why you'd want to do this though.

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


回答2:

Since PHPExcel writes the file to the disk in any case, if you capture stdout, what happens internally is that the file is written to the disk, then read from the disk (and deleted), printed to stdout and then captured in the output buffer.

You might as well do:

$tmpfile = tempnam($tmp_dir, 'phpxltmp');

$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save($tmpfile);

$excelOutput = file_get_contents($tmpfile);
unlink($tmpfile);


标签: phpexcel