protected void Button1_Click(object sender, EventArgs e)
{
Export("application/ms-excel", "學生成績報表.xls");
}
private void Export(string FileType, string FileName)
{
//如下三行可選,若是沒有的話導出的只是當前頁數據,沒有其餘頁數據
GridView1.AllowPaging = false;
GridView1.AllowSorting = false;
gridviewdatabind(); //這裏是你綁定gridview的方法
Response.Charset = "GB2312";
Response.ContentEncoding = System.Text.Encoding.UTF7;
Response.AppendHeader("Content-Disposition", "p_w_upload;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
Response.ContentType = FileType;
this.EnableViewState = false;
StringWriter tw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(tw);
GridView1.RenderControl(hw);
Response.Write(tw.ToString());
Response.End();
}
//
若是沒有下面方法會報錯類型「GridView」的控件「GridView1」必須放在具備 runat=server 的窗體標記內
public override void VerifyRenderingInServerForm(Control control)
{
}
若是你導出時出現以下「
只能在執行 Render() 的過程當中調用 RegisterForEventValidation的錯誤提示錯誤」時,解決方案是:
有兩種方法能夠解決以上問題:
1.修改web.config(不推薦)
<pages enableEventValidation ="false" ></pages>
2.直接在導出Execl的頁面修改
<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"
CodeFile="ExportGridView.aspx.cs" Inherits="ExportGridView" %>