.net 将GrideView导出为EXCEL 却把整个页面都导出来了
[code=C#][/code] Response.Clear();
Response.Buffer = true;
Response.Charset = "utf-8";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + Server.UrlEncode(filename));
// Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文
//Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
// Response.ContentType = "application/excel";
Response.ContentType = "application/vnd.ms-excel";
this.EnableViewState = false;
System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN", true);
System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad);
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
ToExcelGrid.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
HttpContext.Current.ApplicationInstance.CompleteRequest();
------解决方案--------------------
我前几天也在纠结这个问题。
lz在前台页面加一个EnableEventValidation="false"
例如
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Default" EnableEventValidation="false"%>
------解决方案--------------------
看下面的详细步骤!
C# code
1//注意引入IO空间
using System.IO;
2(1)在源代码<page>里中加入:EnableEventValidation = "false"
(2) public void ExcelOut(GridView gv)
{//导出Excel表的方法
if (gv.Rows.Count > 0)
{//有数据行
Response.Clear();
Response.ClearContent();
Response.AddHeader("Content-Disposition","attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");//以系统时间设置为文件名
Response.ContentEncoding = System.Text.Encoding.UTF8;//UTF8编码
Response.ContentType = "application/ms-excel";//文件类型
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Write(sw.ToString());
Response.Flush();
Response.End();//结束
}
else
{
Response.Write("没有数据记录");
}
}
(3) protected void Button1_Click(object sender, EventArgs e)
{//导出按钮事件
ExcelOut(GridView1);//调用方法
}
(4)public override void VerifyRenderingInServerForm(Control control)//必须有这个方法,这个方法就是空方法,不用加任何东西
{ }