All articles(网络文学目录) All Pictures(图片目录) All Softwares(软件目录)

 
将DataGrid或GridView中的数据生成Excel_[Asp.Net教程]

Writer: 归海一刀 Article type: Programming skills(编程技巧) Time: 2014/1/30 1:10:20 Browse times: 338 Comment times: 0

将DataGrid或GridView中的数据生成Excel_[Asp.Net教程]


Head photo

Go homepage
Upload pictures
Write articles

将DataGrid或GridView中的数据生成Excel_[Asp.Net教程]

下面是一个将DataGrid中的数据生成Excel文档的方法,其中System.Web.UI.Control ctl指DataGrid的ID,

FileName指要生成Excel文件的名称。

//生成Excel文件
public void ToExcel(System.Web.UI.Control ctl, string FileName)
{
//设置网络输出流的HTTP字符集为UTF-8,Current为当前 HTTP 请求获取 HttpContext 对象
HttpContext.Current.Response.Charset = "GB2312";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default;
//设置输出流HTTPMIME类型为excel
HttpContext.Current.Response.ContentType = "application/ms-excel";
//将HTTP头添加到输出流
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+ FileName+".xls");
//不保存该控件的视图状态
ctl.Page.EnableViewState = false;
System.IO.StringWriter sw = new System.IO.StringWriter();
//将文本写入到输出流
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(sw);
//将服务器控件的内容输出到HtmlTextWriter对象中
ctl.RenderControl(hw);
//StringWriter.ToString返回包含迄今为止写入到当前 StringWriter 中的字符的字符串
HttpContext.Current.Response.Write(sw.ToString());
HttpContext.Current.Response.End();

}





There are 0 records,
Comment:
Must be registered users to comment(必须是注册用户才能发表评论)

Disclaimer Privacy Policy About us Site Map
Copyright ©2011-
uuhomepage.com, Inc. All rights reserved.