C# 匯出 資料 到Excel

來源:互聯網
上載者:User

標籤:

/// <summary>        /// 實現將資料匯出至Excel,        /// 在上面的代碼中,我們首先將gridview綁定到指定的資料來源中,然後在button1的按鈕(用來做匯出到EXCEL的)的事件中,寫入相關的代碼。        /// 這裡使用Response.AddHeader("content-disposition","attachment;filename= exporttoexcel.xls");中的filename來指定將要匯出的excel的檔案名稱,        /// 這裡是exporttoexcel.xls。要注意的是,由於gridview的內容可能是分頁顯示的,因此,這裡在每次匯出excel時,先將gridview的allowpaging屬性設定為 false,        /// 然後通過頁面流的方式匯出當前頁的gridview到excel中,最後再重新設定其allowpaging屬性。另外要注意的是,要寫一個空的VerifyRenderingInServerForm方法(必須寫),        /// 以確認在運行時為指定的ASP.NET 伺服器控制項呈現HtmlForm 控制項        /// ****************************************************************        /// 以下代碼部份來自互連網        /// 匯出資料到FileName.xls*****************        /// </summary>        /// <param name="sender"></param>        /// <param name="e"></param>        protected void button1_Click(object sender, EventArgs e)        {            Response.Clear();            Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");            Response.Charset = "gb2312";            Response.ContentType = "application/vnd.xls";            System.IO.StringWriter stringWrite = new System.IO.StringWriter();            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);            this.gridview1.AllowPaging = false;            this.bind();            this.gridview1.RenderControl(htmlWrite);            Response.Write(stringWrite.ToString());            Response.End();            this.gridview1.AllowPaging = true;            this.bind();        }

這些代碼寫完之後 ,匯出 資料時,報錯了: 只能在執行 Render() 的過程中調用 RegisterForEventValidation

於是百度,在對應的頁面上,加上EnableEventValidation="false",問題 解決。

參考相關連結:http://www.ezloo.com/2008/10/render_registerforeventvalidation.html

原子中的各位親,如果 發現 有問題,或有更高明的方法,歡迎拍磚!

C# 匯出 資料 到Excel

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.