GridView導出到Excel的一個很簡單實用的列子

     GridView導出到Excel的一個很簡單實用的列子

     項目有個需求是是要把當前數據庫中幾個有關聯的表中數據導出到一張Excel表中,方便參考,後面經過一番搜索和實踐,最後成功實現該功能,現把自己實現的代碼貼出來供大家參考,只是參考,各位看官有更好的方法或者效率方面更好的可以貼出來,大家一起學習,廢話不多說,直接上代碼和實現結果截圖。
前臺代碼:
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" Height="227px"
            Width="100%">
            <Columns>
                <asp:TemplateField>
                    <HeaderTemplate>
                        類別
                    </HeaderTemplate>
                    <ItemTemplate>
                    <asp:Label ID="lb_type" runat="server" Text='<%#Eval("OBJ_WebSiteCategory.website_category_name") %>'></asp:Label>
                    </ItemTemplate>
<%--                    <EditItemTemplate>
                        <asp:Label ID="lb_type" runat="server" Text="<%#Eval('OBJ_WebSiteCategory.website_category_name') %>"></asp:Label>
                    </EditItemTemplate>--%>
                </asp:TemplateField>
                <asp:BoundField DataField="website_pc_productname" HeaderText="商品名" />
                <asp:BoundField DataField="website_pc_url" HeaderText="商品地址" />
                <asp:BoundField DataField="website_pc_sells" HeaderText="銷量" />
            </Columns>
        </asp:GridView>
後臺代碼:
 protected void Page_Load(object sender, EventArgs e)
    {
        WebSiteProduct[] wps = new WebSiteProduct(Operator).SFunc_GetProductsByCategoryId(-1);
        GridView1.DataSource = wps;
        GridView1.DataBind();
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        DataToExcel(this, GridView1);
    }
    public static void DataToExcel(Page p, Control c)
    {
        p.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
        p.Response.Charset = "";

        p.Response.ContentType = "application/vnd.ms-excel";
        p.EnableViewState = false;

        System.IO.StringWriter tw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(tw);


        p.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode("彙總報表.xls", System.Text.Encoding.UTF8));
        c.RenderControl(hw);
        p.Response.Write(tw.ToString());
        p.Response.End();

    }
//必須加上這句,不然直接會報錯
    public override void VerifyRenderingInServerForm(Control control)
    {
    }
這裏有幾個地方要解釋下:
1、 <asp:Label ID="lb_type" runat="server" Text='<%#Eval("OBJ_WebSiteCategory.website_category_name") %>'></asp:Label>,這個是和這個對象關聯的表中的類別字段名
2、WebSiteProduct[] wps = new WebSiteProduct(Operator).SFunc_GetProductsByCategoryId(-1);,這是獲取這個列表的集合,只是實現方式不同而已,實際就看做你獲取的對象集合而已
最後來個圖,有圖有真相:


就這麼多,代碼很簡潔,實現這些功能實際還有很多方法,下次有時間來個大總結吧。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章