PHPExcel不生成正确的xls文件
问题描述:
我在我的项目中使用PHPExcel生成来自数据库的xls文件数据。我在我的PHP类下载PHPExcel的库,并用它作为在下面给出:PHPExcel不生成正确的xls文件
Class name : A.class.php
Path : inside a folder named "inc";
PHPExcel Lib folder : inside "inc" and relative to A.class.php
class A{
// code stuff
public function phpexcelgenerate()
{
require_once 'PHPExcel_1.7.9_doc/Classes/PHPExcel.php';
header('Content-Type: application/vnd.ms-excel');
header('Content-Disposition: attachment;filename="sam.xlsx"');
header('Cache-Control: max-age=0');
$objPHPExcel = new PHPExcel;
$objPHPExcel->setActiveSheetIndex(0);
$objPHPExcel->getActiveSheet()->SetCellValue('A1', "12");
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
// This line will force the file to download
$writer->save();
}
// code stuff
}
此代码生成xls文件,但该文件是完全空的。我在想,我已经在PHP类中以错误的方式包含了PHPExcel的文件。任何人都可以告诉我我做错了什么或者一个例子我怎么能做同样的事情?
答
您需要将文件名传递给save()
方法。然后阅读该文件的内容并回显给浏览器。
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$writer->save("excel.xls");
readfile("excel.xls");
答
首先,你需要阅读的文件:
//get data
$details = $this->main_model->get_details()->row();
然后分配数据来纠正细胞:
$objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $i);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$row, $rec->eType);
// Read the file
$objReader = PHPExcel_IOFactory::createReader(Excel5);
$objPHPExcel = $objReader->load($fileName);
现在从数据库获取数据
最后写入新文件:
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cache
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
//force user to download the Excel file without writing it to server's HD
$objWriter->save('php://output');
+1对于这样一个信息丰富的答案! – goseo