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

来源:互联网 发布:无线网络规划软件 编辑:程序博客网 时间:2024/06/02 08:08

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

具体方法如下:

1、首先派生一个子类,添加一个action成员,在该视图的init函数中判断是浏览动作还是数据导出动作,如果是浏览动作者则保持默认行为,否则输出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、然后在表格控件界面上添加一个csv导出按钮

覆盖其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、然后在点击CSV的动作处理比如actionCsv()中render单个表格视图,模板如下

<?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输出函数中的header设置语句之前不要有任何的输出,包括如下函数:

print, echo, printf, trigger_error, vprintf, ob_flush, var_dump, readfile, passthru

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


by iefreer


参考:

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

原创粉丝点击