asp.net2.0 GridView 导出到 Excel
step 1:
在再这页的aspx文件<%@ Page Language="C#" AutoEventWireup="true" %>
中加上EnableEventValidation="false"
step 2:
把这段代码加在cs 文件中
public override void VerifyRenderingInServerForm(Control control)
{
// base.VerifyRenderingInServerForm(control);
}
step 3:
后台(1)
protected void btnExcel_Click(object sender, EventArgs e)
{
//导出到excel
GVStaff.AllowPaging = false;
Response.Clear();
Response.Buffer = true;
Response.Charset = "GB2312";
Response.AppendHeader("Content-Disposition", "attachment;filename=人员信息.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");//设置输出流为简体中文
Response.ContentType = "application/ms-excel";//设置输出文件类型为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);
GV1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
后台(2)
protected void Button1_Click(object sender, EventArgs e)
{
System.Web.UI.Control ctl = GridView1;
bool CurrCtlVisible = ctl.Visible;
ctl.Visible = true;
Response.AppendHeader("Content-Disposition", "attachment;filename=Excel.xls");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
Response.ContentType = "application/ms-excel";
ctl.Page.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);
ctl.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
ctl.Page.EnableViewState = true;
ctl.Visible = CurrCtlVisible;
}