zl程序教程

您现在的位置是:首页 >  工具

当前栏目

ASP.NET之导出Excel——无乱码现象

NetExcelASP导出 乱码 现象
2023-09-14 09:16:29 时间

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” 引号中填写当前页面后台代码的文件名称(全称)