将GridView中的数据导出到Excel中下载并且解决乱码的问题
将GridView中的数据导出到Excel中下载并且解决乱码的问题
在软件开发过程中我们经常将GridView中的数据导出到Excel中供客户端下载,以下提供一种解决供参考,欢迎大家讨论并提出其中的不足,以达到相互学习共同提高.
步骤1:
添加如下事件到GridView所在的页面
//下载GridView,添加如下事件;
public override void VerifyRenderingInServerForm(Control control)
{
}
public override void VerifyRenderingInServerForm(Control control)
{
}
步骤2:
调用的方法如下
/// </summary>
/// <param name="g">要下载的GridView</param>
/// <param name="fileName">文件名;</param>
/// <param name="table">数据源,为了解决分页问题</param>
public static void DownLoad(GridView g,string fileName,DataTable table)
{
g.DataSource = table;
g.AllowPaging = false;
g.DataBind();
fileName = HttpUtility.UrlEncode(fileName + ".xls", Encoding.GetEncoding("utf-8"));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
//Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");//即可导成word;
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
ShowGridViewHeader.OnlyShowGridViewHeader(g);
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
g.RenderControl(htmlWrite);
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.End();
}
/// <param name="g">要下载的GridView</param>
/// <param name="fileName">文件名;</param>
/// <param name="table">数据源,为了解决分页问题</param>
public static void DownLoad(GridView g,string fileName,DataTable table)
{
g.DataSource = table;
g.AllowPaging = false;
g.DataBind();
fileName = HttpUtility.UrlEncode(fileName + ".xls", Encoding.GetEncoding("utf-8"));
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=text/html;charset=utf-8>");
//Response.AddHeader("content-disposition", "attachment;filename=FileName.doc");//即可导成word;
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
ShowGridViewHeader.OnlyShowGridViewHeader(g);
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
g.RenderControl(htmlWrite);
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.End();
}
通过以上两个步骤就可以实现对GridView中数据的导出与下载,如果你在下载后没有出现乱码现象,那么真的很恭喜你.对于数据的下载有的计算机会出现乱码现象,而有的计算机不会.解决方案如下:
解决方法
1.保存的文件名不能使用中文,如果想使用中文请对其进行编码;
2.配置web.config代码如下
<system.web>
<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
</system.web>
<globalization requestEncoding="utf-8" responseEncoding="utf-8"/>
</system.web>
(作者:侯垒)