/// <summary> /// 導出按鈕 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnExport_Click1(object sender, EventArgs e) { this.gv.AllowPaging = false; this.gv.AllowSorting = false; Query();//獲取數據並綁定到GridView toExcel(this.gv); this.gv.AllowPaging = true; this.gv.AllowSorting = true; Query();//獲取數據並綁定到GridView } /// <summary> /// 導出到Excel /// </summary> /// <param name="gv"></param> void toExcel(GridView gv){ Response.Charset = "GB2312"; Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); string fileName = "export.xls"; string style = @"<style> .text { mso-number-format:\@; } </script> "; Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=" + fileName); Response.ContentType = "application/excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); this.gv.RenderControl(htw); Response.Write(style); Response.Write(sw.ToString()); Response.End(); } /// <summary> /// 這個重寫貌似是必須的 /// </summary> /// <param name="control"></param> public override void VerifyRenderingInServerForm(Control control) { }
備註:c#
一、gv就是頁面上的GridView空間名稱;app
二、代碼中的Query方法所作的是,獲取數據並綁定到GridView。ide