GridView控件导出Excel的方式及部分错误解决方案
ASP.net导出的Excel并非真正的Excel
- 导出Excel核心代码
//清除缓冲中的所有内容输出Response.Clear();//设置输入流的http字符集Response.Charset = \"GB2312\"; //中文字符编码//设置是否缓冲输出并在处理完整个响应之后发送它Response.Buffer = true;//将http的头添加到输出流 设置导出后文件名称Response.AppendHeader(\"Content-Disposition\", \"attachment;filename=用户信息.xls\");//设置输出内容的编码格式Response.ContentEncoding = System.Text.UTF8Encoding.GetEncoding(\"GB2312\");//设置输出流的http mime类型Response.ContentType = \"application/ms-excel\";//实例化一个用于写入字符串的对象System.IO.StringWriter sw = new System.IO.StringWriter();//将文本写入到asp.net服务器控件输出流System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);//隐藏选择列,不导出选择列,列索引从0开始gvUserInfo.Columns[0].Visible = false;//导出前先取消分页,以便能将所有数据导出。gvUserInfo.AllowPaging = false;//将GridView控件内容输出至服务器gvUserInfo.RenderControl(htw);//以异步的形式将字符串写入到文本字符或者流Response.Output.Write(sw.ToString());//向客户端发送当前缓冲的输出Response.Flush();//停止输出Response.End();/// <summary>/// 必须重写VerifyRenderingInServerForm方法/// </summary>/// <param name=\"control\"></param>public override void VerifyRenderingInServerForm(Control control){}
错误1:没有重写
VerifyRenderingInServerForm()
方法
解决方案:重写
VerifyRenderingInServerForm()
方法
错误2:导出Excel时只能在执行 Render() 的过程中调用 RegisterForEventValidation
解决方案:
在此
<%@ Page Language=\"C#\" AutoEventWireup=\"true\" Inherits=\"UI.AdminMain\" %>
代码段中加入
EnableEventValidation = \"false\" CodeFile=\"AdminMain.aspx.cs\"
CodeFile=“AdminMain.aspx.cs” 引号中填写当前页面后台代码的文件名称(全称)
- 点赞1
- 收藏
- 分享
- 文章举报
黑夜中的潜行者发布了25 篇原创文章 · 获赞 18 · 访问量 897私信关注