從GridView匯出Excel

於WebPage宣告上的設定
必須在加入EnableEventValidation = "false"
如:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="xxxx.aspx.cs" Inherits="xxxx" EnableEventValidation="false" %>

於WebPage必須Override的Function
為了避免Page格式檢查發生錯誤,必須改寫此function:
public override void VerifyRenderingInServerForm(Control control)    {}

Export Sample
private void ExportGridView(GridView gv, string fileName)
{
    string attachment = "attachment; filename=" + fileName;
    Response.ClearContent();
    Response.AddHeader("content-disposition", attachment);
    Response.ContentType = "application/ms-excel";
    Response.Charset = "big5";
    Response.ContentEncoding = System.Text.Encoding.GetEncoding("big5");
    StringWriter sw = new StringWriter();
    HtmlTextWriter htw = new HtmlTextWriter(sw);
    gv.AllowPaging = false;
    gv.AllowSorting = false;
    gv.DataBind();
    gv.RenderControl(htw);
    Response.Write(sw.ToString());
    Response.End();
}

沒有留言:

橫式廣告