天天看點

将GridView資料導出到Excel實作

最近想整理一些詞庫,懶得手動找,又怕手一哆嗦有遺漏,決定寫程式完成吧。

首先将資料用GridView控件顯示到頁面上,效果如下:

接下來将GridView中的内容導出到Excel,方法如下:

<a></a>

 /// &lt;summary&gt;

    /// 由GridView導出Excel

    /// &lt;/summary&gt;

    /// &lt;param name="ctl"&gt;GridView控件ID&lt;/param&gt;

    /// &lt;param name="FileName"&gt;導出Excel名稱&lt;/param&gt;

    private void ToExcel(Control ctl, string FileName)

    {

        HttpContext.Current.Response.Charset = "UTF-8";

        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;

        HttpContext.Current.Response.ContentType = "application/ms-excel";

        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + "" + FileName);

        ctl.Page.EnableViewState = false;

        System.IO.StringWriter tw = new System.IO.StringWriter();

        HtmlTextWriter hw = new HtmlTextWriter(tw);

        ctl.RenderControl(hw);

        HttpContext.Current.Response.Write(tw.ToString());

        HttpContext.Current.Response.End();

    }

在按鈕上添加事件來導出Excel。注意,因為GridView是有分頁和排序設定的,為了能夠顯示完整的資料,要先取消分頁排序,導出之後再恢複設定。代碼如下:

  protected void btnExport_Click(object sender, EventArgs e)

        gvWord.AllowPaging = false;

        gvWord.AllowSorting = false;

        Display();

        ToExcel(gvWord, "word.xls");

        gvWord.AllowSorting = true;

        gvWord.AllowPaging = true;

可是運作之後報錯:

類型“GridView”的控件“GridView1”必須放在具有 runat=server 的窗體标記内。

添加重寫方法:

 public override void VerifyRenderingInServerForm(Control control)

        //base.VerifyRenderingInServerForm(control);

完成後效果如下:

這下可以讓程式幫我整理了,省了一筆麻煩啊。

    本文轉自 陳敬(Cathy) 部落格園部落格,原文連結:http://www.cnblogs.com/janes/archive/2011/01/05/1926161.html,如需轉載請自行聯系原作者

繼續閱讀