本文實例講述了Yii Framework框架使用PHPExcel組件的方法。分享給大家供大家參考,具體如下:
PHPExcel下載地址http://www.yiiframework.com/extension/phpexcel
將下載的PHPExcel壓縮包解壓到Yii Framework目錄framework\vendors下
代碼如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
/** * 將數據導出到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' )); } |
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。
原文鏈接:https://www.cnblogs.com/lingyun_k/archive/2010/11/09/1872891.html