我在我的项目中使用PHPExcel来生成来自数据库的xls数据文件。我已经下载了PHPExcel库并在我的PHP类中使用它,如下所示:
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的文件。任何人都可以告诉我我在哪里做错了或者一个例子我该怎么做?
答案 0 :(得分:2)
您需要将文件名传递给save()
方法。然后读取该文件的内容并回显到浏览器。
$writer = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$writer->save("excel.xls");
readfile("excel.xls");
答案 1 :(得分:2)
首先你需要阅读文件:
// Read the file
$objReader = PHPExcel_IOFactory::createReader(Excel5);
$objPHPExcel = $objReader->load($fileName);
现在从db获取数据:
//get data
$details = $this->main_model->get_details()->row();
然后将数据分配给正确的单元格:
$objPHPExcel->getActiveSheet()->setCellValue('A'.$row, $i);
$objPHPExcel->getActiveSheet()->setCellValue('B'.$row, $rec->eType);
最后写下新文件:
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');