GridView匯出Excel

  • 5681
  • 0
  • C#
  • 2013-09-25

GridView匯出Excel

要在Page加上 EnableEventValidation="false" 比較不會有問題

 

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="BSMIS_BREMPLOYEES_STAT.aspx.cs" Inherits="_Default" EnableEventValidation="false"  %>
    protected void btnExportExcel_Click(object sender, EventArgs e)
    {
        #region "匯出Excel"
        DataView dvSql = (DataView)SqlDataSource1.Select(DataSourceSelectArguments.Empty);
        if (dvSql.Count == 0)
        {
            return;
        }
        DataRow drvSql = dvSql[0].Row;
        Response.Clear();
        Response.AddHeader("content-disposition", "attachment;filename=PoolExport.xls");
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htw = new HtmlTextWriter(sw);
        //關閉換頁跟排序
        GridView1.AllowSorting = false;
        GridView1.AllowPaging = false;
        GridView1.DataBind();
        //建立假HtmlForm避免以下錯誤
        //Control 'GridView1' of type 'GridView' must be placed inside 
        //a form tag with runat=server. 
        //另一種做法是override VerifyRenderingInServerForm後不做任何事
        //這樣就可以直接GridView1.RenderControl(htw);
        HtmlForm hf = new HtmlForm();
        Controls.Add(hf);
        hf.Controls.Add(GridView1);
        hf.RenderControl(htw);
        Response.Write(sw.ToString());
        Response.End();
        #endregion      
    }