Asp.net中匯出成Excel等格式

來源:互聯網
上載者:User

我們做一個測試程式:
1、在空白頁上建立一個GridView,給它指定一個資料來源,填充一些測試資料(此例中是GridView1)。
2、給頁面添加一個按鈕(此例中是btnExport),在按鈕的單擊事件中填入如下代碼:
protected void btnExport_Click(object sender, EventArgs e)
{
        Response.Clear();
        Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
        Response.AppendHeader("content-disposition", "attachment;filename=\"" + HttpUtility.UrlEncode("[" + DateTime.Now.ToString("yyyy-MM-dd") + "]", System.Text.Encoding.UTF8) + ".xls\"");
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
        // If you want the option to open the Excel file without saving then
        // comment out the line below
        //Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());
        Response.End();
}
3、重載方法VerifyRenderingInServerForm,否則VS編譯器報錯。
public override void VerifyRenderingInServerForm(Control control)
{
}
4、運行頁面,單擊按鈕,彈出提示框,要你選擇儲存或開啟一個以目前時間命名的Excel檔案。

注意事項:若表格中有中文必須將編碼格式設定為gb2312,如下:
Response.Write("<meta http-equiv=Content-Type content=text/html;charset=gb2312>");
Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
必須重載VerifyRenderingInServerForm方法。
還可以匯出成各種形式的文檔,只需把Response.ContentType的值設定成別的就可以,具體值可以從網上查到,如要匯出成Word格式可以將Response.ContentType的值設定成"application/word.doc"。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.