zoukankan
html css js c++ java
GridView数据导出到Excel的类
今天碰到个问题,需要根据设置把GridView中的数据中的一页或全部导出到Excel表中,
故新写一个类,希望对各位友人有帮助。本类的基本难点说明中都已经做备注,有不明白
可以直接联系。
Code
/**/
///
<summary>
///
把Gridview中数据导入到Excel的类
///
</summary>
public
class
GridViewToExcel
{
public
GridViewToExcel()
{
//
//
TODO: 在此处添加构造函数逻辑
//
}
/**/
///
<summary>
///
///
把Gridview中数据导入到Excel中
///
</summary>
///
<param name="gv">
需要导出数据的Gridview
</param>
///
<param name="ds">
Gridview的数据源
</param>
///
<param name="strFileName">
默认的导出Excel的文件名
</param>
///
<param name="bolPart">
全部还是部分导出到Excel.部分:true. 全部:false
</param>
public
static
void
ConvertToExcel(GridView gv, DataSet ds,
string
strFileName,
bool
bolPart)
{
gv.AllowPaging
=
bolPart;
//
设置导出数据是全部还是部分
gv.DataSource
=
ds;
gv.DataBind();
for
(
int
i
=
0
; i
<
gv.Columns.Count; i
++
)
//
设置每个单元格
{
gv.Columns[i].ItemStyle.HorizontalAlign
=
HorizontalAlign.Left;
for
(
int
j
=
0
; j
<
gv.Rows.Count; j
++
)
{
gv.Rows[j].Cells[i].Attributes.Add(
"
style
"
,
"
vnd.ms-excel.numberformat:@;
"
);
}
}
System.IO.StringWriter sw
=
new
System.IO.StringWriter();
HtmlTextWriter htw
=
new
HtmlTextWriter(sw);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.Charset
=
"
GB2312
"
;
HttpContext.Current.Response.ContentEncoding
=
System.Text.Encoding.UTF7;
//
设置UTF8有时候出乱码
strFileName
+=
"
.xls
"
;
HttpContext.Current.Response.ContentType
=
"
application/ms-excel
"
;
HttpContext.Current.Response.AddHeader(
"
content-disposition
"
,
"
attachment;filename=
"
+
HttpUtility.UrlPathEncode(strFileName));
//
设置默认文件名
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
//
预防出现控件必须放在具有 runat=server 的窗体标记内的错误
Page page
=
new
Page();
HtmlForm form
=
new
HtmlForm();
gv.EnableViewState
=
false
;
page.EnableEventValidation
=
false
;
page.DesignerInitialize();
page.Controls.Add(form);
form.Controls.Add(gv);
page.RenderControl(htw);
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();
}
}
查看全文
相关阅读:
个人理财小助手 —— 简介
我的分页控件(未完,待续)——控件件介绍及思路
静态变量 静态对象 静态函数和非静态函数的区别。(我的理解,大家看看对不对)
通过“访问多种数据库”的代码来学习多态!(.net2.0版)
Step By Step 一步一步写网站[1] —— 填加数据
个人理财小助手 —— 数据库(一)
几个鸟叫的声音
Step By Step 一步一步写网站[1] —— 帧间压缩,表单控件
面向对象相关
论程序的成长—— 你写的代码有生命力吗?
原文地址:https://www.cnblogs.com/zijinguang/p/1509564.html
最新文章
HTML里面include其他文件的方法
水晶报表分栏显示
使用Media Player控件播放MP3
CRC循环冗余错误校验计算方法
定义Bash提示符中显示IP
RTSP协议详解
做局域网yum源
MySQL查看表占用空间大小(转)
淘宝技术发展(转)
linux alias命令参数及用法详解linux定义命令别名alias
热门文章
MySQL索引背后的数据结构及算法原理(转)
HTTP协议之缓存(转)
一致性Hash算法背景(转)
组合博弈游戏
CentOS源码编译安装MySQL 5.5.15(转)
【转】[转载]用c写PHP的扩展接口(php5,c++)
mysql 增加用户
Linux/Ubuntu下C语言开发PHP的.so扩展模块过程
HTTP Cache
我的数据访问类(第二版)—— for .net2.0 (二)
Copyright © 2011-2022 走看看