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" %>