您的位置:首页 > 编程语言 > ASP

asp.net中将GridView数据导出成Excel文件(下)

2013-03-13 17:51 696 查看

asp.net中将GridView数据导出成Excel文件(下)

///
导出GridView中的数据到Excel

private
static void GoToExcel(GridView
gvw,string
title)

{

string
fileName;

HttpContext.Current.Response.Buffer
= true;

HttpContext.Current.Response.ClearContent();

HttpContext.Current.Response.ClearHeaders();

fileName
= string.Format("Export-File
{0:yyyy-MM-dd_HH_mm}.xls",
DateTime.Now);
//生成导出文件名

HttpContext.Current.Response.AppendHeader("Content-Disposition",
"attachment;filename="
+ fileName);
//关联要生成的文件

HttpContext.Current.Response.ContentType
= "application/vnd.ms-excel";

StringWriter
tw =
new System.IO.StringWriter();
//创建StringWriter对象实例

HtmlTextWriter
hw =
new System.Web.UI.HtmlTextWriter(tw);

//根据StringWriter对象创建HtmlTextWriter对象实例

gvw.RenderControl(hw);
//将GridView内输入HtmlTextWriter中,并跟踪信息

if
(!string.IsNullOrEmpty(title))
//如果
title 不为空则加入title内容

{

HttpContext.Current.Response.Write("<b><center><font
size=3 face=Verdana color=#0000FF>" +title
+"</font></center></b>");
}

HttpContext.Current.Response.Write(tw.ToString());
//正真写入内容到文件

HttpContext.Current.Response.Flush();

HttpContext.Current.Response.Close();

HttpContext.Current.Response.End();

gvw.Dispose();
//释放过程中的对象实例

tw.Dispose();

hw.Dispose();

gvw
= null;

tw
= null;

hw
= null;

}

}

}


调用示例:
List
orders=this.
GetOrders();
// 得到ist数据

ToExcel.ExportToExcel(orders,

new
string[] {
"OrderNo",
"CustomerNo",
"UserNo",
"ModelNo","Quantity","Price","Amount","OrderDate"
},

new
string[] {
"订单","客户代码","用户代码","型号","数量","价格","金额","订货日期"}
);


http://blog.sina.com.cn/s/blog_4d174ff90100i4dd.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: