Yii CGridView 扩展 CSV 导出功能概述
本示例介绍如何在Yii框架中为CGridView组件扩展CSV数据导出功能,供开发者参考实践。
Yii自带的CGridView组件并未内置数据导出能力,但可通过继承扩展的方式为该组件添加此功能。
具体实现步骤如下:
首先创建一个子类,新增一个action成员变量。在该视图的init函数中判断当前是浏览模式还是导出模式:若为浏览则执行默认行为,若为导出则生成并输出CSV文件。
public function init()
{
if($this->action == 'export')
{
parent::init();
$this->genCsv();
}
else
{
parent::init();
}
}
其次处理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();
}
接着在表格控件界面上增加一个用于触发CSV导出的按钮。
覆盖其renderItems()方法如下:
public function renderItems()
{
if(Yii::app()->user->checkAccess('administrator'))
{
echo '';
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 '';
}
parent::renderItems();
}
随后在处理CSV点击动作(如actionCsv())时渲染单个表格视图,模板代码如下:
<?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
否则内容仅会在浏览器页面中显示,而不会触发文件下载对话框。
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。