GridView导出到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) { }这里有几个地方要解释下: