Yii: 扩展CGridView增加导出CSV功能

Yii提供的CGridView组件没有内置数据导出功能,不过我们可以通过扩展该组件来添加该功能。

具体方法如下:

1、首先派生一个子类,添加一个action成员,在该视图的init函数中判断是浏览动作还是数据导出动作,如果是浏览动作者则保持默认行为,否则输出csv文件。

[php] view plaincopy
 
  1. public function init()  
  2. {  
  3.     if($this->action == 'export')  
  4.     {  
  5.         parent::init();  
  6.         $this->genCsv();  
  7.     }  
  8.     else  
  9.     {  
  10.         parent::init();  
  11.     }  
  12. }  

 

2、处理csv文件的输出:

 

[php] view plaincopy
 
  1.         protected function genCsv()  
  2.         {  
  3.             header("Content-Type: text/csv; charset=GB2312");  
  4.             header('Content-Disposition: attachment; filename="'.$this->fileName.'"');  
  5.               
  6.             //add your content dump codes here  
  7.   
  8.             flush();  
  9.   
  10.         }  

 

 

3、然后在表格控件界面上添加一个csv导出按钮

 

覆盖其renderItems()方法如下:

[php] view plaincopy
 
  1. public function renderItems()  
  2. {  
  3.     if(Yii::app()->user->checkAccess('administrator'))  
  4.     {  
  5.         echo '<div class="toolBar">';  
  6.         echo '<form action="'.CHtml::normalizeUrl(array($this->action)).'&id='.$this->id.'" method="post">';  
  7.         foreach($this->getController()->getActionParams() as $name => $value)  
  8.         {  
  9.             echo '<input type="hidden" name="'.addcslashes($name,'"').'" value="'.addcslashes($value,'"').'" />';  
  10.         }  
  11.         echo '<input type="image" title="'.Yii::t('ifCMS','Export to CSV').'" src="'.Yii::app()->theme->BaseUrl.'/images/ico-csv.png" alt="Submit">';  
  12.         echo '</form>';  
  13.         echo '</div>';  
  14.     }  
  15.     parent::renderItems();  
  16.      }  

 

4、然后在点击CSV的动作处理比如actionCsv()中render单个表格视图,模板如下

 

[php] view plaincopy
 
  1. <?php   
  2.     $this->widget('application.extensions.grid.MyGridView', array(  
  3.     'id'=>'grid',  
  4.     'action'=>'export',  
  5.     'dataProvider'=>$dp,  
  6.     'columns'=>array(  
  7.         array(  
  8.             'header'=>Yii::t('Statistics','Phone'),  
  9.             'name'=>'phone',  
  10.         ),  
  11.         array(  
  12.             'header'=>Yii::t('Statistics','Count'),  
  13.             'name'=>'count',  
  14.         ),  
  15.     )  
  16. ));?>  

 

 

注意上述第2步csv输出函数中的header设置语句之前不要有任何的输出,包括如下函数:

 

[plain] view plaincopy
 
  1. print, echo, printf, trigger_error, vprintf, ob_flush, var_dump, readfile, passthru  

 

 

否则内容只会在浏览器中输出,但不会出现文件下载。

by iefreer

 

参考:

http://stackoverflow.com/questions/8028957/headers-already-sent-by-php

posted @ 2015-08-21 13:19  还是小黑  阅读(319)  评论(0编辑  收藏  举报