本文實(shí)例講述了Yii框架擴(kuò)展CGridView增加導(dǎo)出CSV功能的方法。分享給大家供大家參考,具體如下:
Yii提供的CGridView組件沒有內(nèi)置數(shù)據(jù)導(dǎo)出功能,不過我們可以通過擴(kuò)展該組件來添加該功能。
具體方法如下:
1、首先派生一個(gè)子類,添加一個(gè)action成員,在該視圖的init函數(shù)中判斷是瀏覽動作還是數(shù)據(jù)導(dǎo)出動作,如果是瀏覽動作者則保持默認(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" title="'.Yii::t('ifCMS','Export to CSV').'" src="'.Yii::app()->theme->BaseUrl.'/images/ico-csv.png" alt="Submit">'; echo '</form>'; echo '</div>'; } parent::renderItems(); }
4、然后在點(diǎn)擊CSV的動作處理比如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è)置語句之前不要有任何的輸出,包括如下函數(shù):
print
, echo
, printf
, trigger_error
, vprintf
, ob_flush
, var_dump
, readfile
, passthru
否則內(nèi)容只會在瀏覽器中輸出,但不會出現(xiàn)文件下載。
更多關(guān)于Yii相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Yii框架入門及常用技巧總結(jié)》、《php優(yōu)秀開發(fā)框架總結(jié)》、《smarty模板入門基礎(chǔ)教程》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php字符串(string)用法總結(jié)》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Yii框架的PHP程序設(shè)計(jì)有所幫助。