iT邦幫忙

0

c# web GridView轉成EXCEL & 頁面輸出

c#
    不知道為什麼只導出GridView,但整個頁面都輸出了.所以只好把不要的區塊visible=false
    
    public void ExportToEXCEL(System.Web.UI.WebControls.GridView gv, string filename, string headtxt)
    { 
        this.dgShow.AllowPaging = false;
        this.dgShow.EnableViewState = false; //把ViewState給關了
        this.dgShow.DataBind();
        plQuery.Visible = false;

        Response.Buffer = true;
        Response.Charset = "UTF-8"; //設定字集
        Response.AppendHeader("Content-Disposition", "attachment;filename=xxx.xls"); //filename 可自定
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        Response.ContentType = "application/ms-excel "; //內容型態設為Excel
        
        System.IO.StringWriter objStringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter objHtmlTextWriter = new System.Web.UI.HtmlTextWriter(objStringWriter);
        //this.RenderControl(objHtmlTextWriter); 
        this.dgShow.RenderControl(objHtmlTextWriter);
        //不知道為什麼只導出dgshow,但整個頁面都輸出了.所以只好把不要的區塊visible=false
        Response.Write(objStringWriter.ToString());
        Response.End();

        this.dgShow.AllowPaging = true;
        this.dgShow.EnableViewState = true; //把ViewState
        this.dgShow.DataBind();
        plQuery.Visible = true;
    }
    public override void VerifyRenderingInServerForm(Control control)
    { 
        // '處理'GridView' 的控制項 'GridView' 必須置於有 runat=server 的表單標記之中  
    }

尚未有邦友留言

立即登入留言