本文实例讲述了Yii框架扩展CGridView增加导出CSV功能的方法。分享给大家供大家参考,具体如下:
Yii提供的CGridView组件没有内置数据导出功能,不过我们可以通过扩展该组件来添加该功能。
具体方法如下:
1、首先派生一个子类,添加一个action成员,在该视图的init函数中判断是浏览动作还是数据导出动作,如果是浏览动作者则保持默认行为,否则输出csv文件。
?
1
2
3
4
5
6
7
8
9
10
11
12
|
public function init()
{
if ( $this ->action == 'export' )
{
parent::init();
$this ->genCsv();
}
else
{
parent::init();
}
}
|
2、处理csv文件的输出:
?
1
2
3
4
5
6
7
|
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()
方法如下:
- publicfunctionrenderItems()
- {
- if(Yii::app()->user->checkAccess('administrator'))
- {
- echo'<divclass="toolBar">';
- echo'<formaction="'.CHtml::normalizeUrl(array($this->action)).'&id='.$this->id.'"method="post">';
- foreach($this->getController()->getActionParams()as$name=>$value)
- {
- echo'<inputtype="hidden"name="'.addcslashes($name,'"').'"value="'.addcslashes($value,'"').'"/>';
- }
- echo'<inputtype="image"title="'.Yii::t('ifCMS','ExporttoCSV').'"src="'.Yii::app()->theme->BaseUrl.'/images/ico-csv.png"alt="Submit">';
- echo'</form>';
- echo'</div>';
- }
- parent::renderItems();
- }
4、然后在点击CSV的动作处理比如actionCsv()
中render单个表格视图,模板如下
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
<?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程序设计有所帮助。
相关文章
猜你喜欢
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
- 个人网站服务器域名解析设置指南:从购买到绑定全流程 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-06-05 25
-
2025-05-27 47
-
2025-05-27 20
-
2025-05-25 27
-
2025-05-25 37
热门评论