這篇文章主要介紹Yii框架擴(kuò)展CGridView如何增加導(dǎo)出CSV功能,文中介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們一定要看完!
具體如下:
Yii提供的CGridView組件沒有內(nèi)置數(shù)據(jù)導(dǎo)出功能,不過我們可以通過擴(kuò)展該組件來添加該功能。
具體方法如下:
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" 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的動(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)文件下載。
以上是“Yii框架擴(kuò)展CGridView如何增加導(dǎo)出CSV功能”這篇文章的所有內(nèi)容,感謝各位的閱讀!希望分享的內(nèi)容對(duì)大家有幫助,更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道!
網(wǎng)站欄目:Yii框架擴(kuò)展CGridView如何增加導(dǎo)出CSV功能-創(chuàng)新互聯(lián)
鏈接地址:http://chinadenli.net/article34/djgjpe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供虛擬主機(jī)、標(biāo)簽優(yōu)化、服務(wù)器托管、品牌網(wǎng)站制作、小程序開發(fā)、企業(yè)網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容