文章來給大家介紹在yii框架中利用PHPExcel插件來快速實例導出excel數據的具體方法,有在使用yii的同學不防進入參考一下.
最近在研究PHP的Yii框架,很喜歡,碰到導出Excel的問題,研究了一下,就有了下面的方法.
1、首先在cofig/main.php中添加對PHPExcel的引用,我的方法是這樣,代碼如下:
- // autoloading model and component classes
- 'import'=>array(
- /*'application.modules.srbac.controllers.SBaseController',*/
- 'application.models.*',
- 'application.components.*',
- 'application.extensions.phpexcel.*',
- ),
2、當然要記得將PHPExcel整個目錄復制到項目的 "protected/extensions/" 目錄下面.
3、按照下面的代碼修改PHPExcel代碼目錄里的Autoloader.php文件,代碼如下:
- public static function Register() {
- /*if (function_exists('__autoload')) {
- // Register any existing autoloader function with SPL, so we don't get any clashes
- spl_autoload_register('__autoload');
- }
- // Register ourselves with SPL
- return spl_autoload_register(array('PHPExcel_Autoloader', 'Load'));*/
- $functions = spl_autoload_functions();
- //開源代碼Vevb.com
- foreach ( $functions as $function)
- spl_autoload_unregister($function);
- $functions = array_merge(array(array('PHPExcel_Autoloader','Load')),$functions);
- foreach ( $functions as $function)
- $x = spl_autoload_register($function);
- return $x;
- } // function Register()
上面的函數中,注釋掉的是原有的代碼.
4、下面的代碼是輸出Excel,以及一些常用的屬性設置,在你的Controller中,代碼如下:
- $objectPHPExcel = new PHPExcel();
- $objectPHPExcel->setActiveSheetIndex(0);
- ob_end_clean();
- ob_start();
- header('Content-Type : application/vnd.ms-excel');
- header('Content-Disposition:attachment;filename="'.'xiaoqiang-'.date("Ymj").'.xls"');
- $objWriter= PHPExcel_IOFactory::createWriter($objectPHPExcel,'Excel5');
- $objWriter->save('php://output');
新聞熱點
疑難解答