本文實(shí)例講述了Yii框架擴(kuò)展CGridView增加導(dǎo)出CSV功能的方法。分享給大家供大家參考,具體如下:
Yii提供的CGridView組件沒(méi)有內(nèi)置數(shù)據(jù)導(dǎo)出功能,不過(guò)我們可以通過(guò)擴(kuò)展該組件來(lái)添加該功能。
具體方法如下:
1、首先派生一個(gè)子類,添加一個(gè)action成員,在該視圖的init函數(shù)中判斷是瀏覽動(dòng)作還是數(shù)據(jù)導(dǎo)出動(dòng)作,如果是瀏覽動(dòng)作者則保持默認(rèn)行為,否則輸出csv文件。
public function init(){  if($this->action == 'export')  {    parent::init();    $this->genCsv();  }  else  {    parent::init();  }}2、處理csv文件的輸出:
protected function genCsv(){  header("Content-Type: text/csv; charset=GB2312");  header('Content-Disposition: attachment; filename="'.$this->fileName.'"');  //add your content dump codes here  flush();}3、然后在表格控件界面上添加一個(gè)csv導(dǎo)出按鈕
	覆蓋其renderItems()方法如下:
public function renderItems(){  if(Yii::app()->user->checkAccess('administrator'))  {    echo '<div class="toolBar">';    echo '<form action="'.CHtml::normalizeUrl(array($this->action)).'&id='.$this->id.'" method="post">';    foreach($this->getController()->getActionParams() as $name => $value)    {      echo '<input type="hidden" name="'.addcslashes($name,'"').'" value="'.addcslashes($value,'"').'" />';    }    echo '<input type="image"   echo '</form>';    echo '</div>';  }  parent::renderItems();}	4、然后在點(diǎn)擊CSV的動(dòng)作處理比如actionCsv()中render單個(gè)表格視圖,模板如下
<?php  $this->widget('application.extensions.grid.MyGridView', array(  'id'=>'grid',  'action'=>'export',  'dataProvider'=>$dp,  'columns'=>array(    array(      'header'=>Yii::t('Statistics','Phone'),      'name'=>'phone',    ),    array(      'header'=>Yii::t('Statistics','Count'),      'name'=>'count',    ),  )));?>注意上述第2步csv輸出函數(shù)中的header設(shè)置語(yǔ)句之前不要有任何的輸出,包括如下函數(shù):
	print, echo, printf, trigger_error, vprintf, ob_flush, var_dump, readfile, passthru
否則內(nèi)容只會(huì)在瀏覽器中輸出,但不會(huì)出現(xiàn)文件下載。
希望本文所述對(duì)大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選