如何在Yii Framework中使用PHPExcel组件【备忘】
PHPExcel下载地址http://www.yiiframework.com/extension/phpexcel
将下载的PHPExcel压缩包解压到Yii Framework目录framework\vendors下
代码如下
/**
* 将数据导出到Excel
*/
public function actionExport()
{
//取要导出到Excel的数据
$criteria = $this->_getCriteria();
$data = Statistics::model()->findAll($criteria);
// 获取PHPExcel引用路径
$phpExcelPath = Yii::getPathOfAlias('system.vendors');
// 关闭YII的自动加载功能,改用手动加载,否则会出错,PHPExcel有自己的自动加载功能
// YII框架对于组件的自动加载,要求类名与文件名一致;
// 而PHPExcel类对应的文件名包含了上级目录名称,如:IOFactory类对应的文件名为PHPExcel_IOFactory.php
spl_autoload_unregister(array('YiiBase','autoload'));
include($phpExcelPath . DIRECTORY_SEPARATOR . 'PHPExcel.php');
//下面是Excel数据导出处理逻辑
$objPHPExcel = PHPExcel_IOFactory::load('./content/template/report.xlsx');
$objPHPExcel->getProperties()->setCreator("Kalman")
->setTitle("统计报表")
->setSubject("统计报表")
->setDescription("统计报表");
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', 'Hello')
->setCellValue('B2', 'world!')
->setCellValue('C1', 'Hello')
->setCellValue('D2', 'world!');
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A25', '123456');
$objPHPExcel->getActiveSheet()->setTitle('report');
// Excel打开后显示的工作表
$objPHPExcel->setActiveSheetIndex(0);
//通浏览器输出Excel报表
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="report.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
Yii::app()->end();
//恢复Yii自动加载功能
spl_autoload_register(array('YiiBase','autoload'));
}