直接上源码不解释:
1 using System; 2 using System.Data; 3 using System.Configuration; 4 using System.Linq; 5 using System.Web; 6 using System.Web.Security; 7 using System.Web.UI; 8 using System.Web.UI.HtmlControls; 9 using System.Web.UI.WebControls; 10 using System.Web.UI.WebControls.WebParts; 11 using System.Xml.Linq; 12 13 14 public static class ExportExcel 15 { 16 public static void ExportByDataSet(DataSet ds, string fileName) 17 { 18 DataTable dtData = ds.Tables[0]; 19 20 //删除列,修改列头显示 21 //dtData.Columns.Remove(""); 22 //dtData.Columns[0].ColumnName = "行ID"; 23 24 dtData.AcceptChanges(); 25 26 System.Web.UI.WebControls.GridView dgExport = null; 27 System.Web.HttpContext curContext = System.Web.HttpContext.Current; 28 System.IO.StringWriter strWriter = null; 29 System.Web.UI.HtmlTextWriter htmlWriter = null; 30 System.Web.HttpContext.Current.Response.Clear(); 31 System.Web.HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("utf-8"); 32 curContext.Response.ContentType = "application/vnd.ms-excel"; 33 34 fileName = fileName + ".xls"; 35 36 curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName)); 37 curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; 38 System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.Default; 39 curContext.Response.Charset = ""; 40 41 strWriter = new System.IO.StringWriter(); 42 htmlWriter = new System.Web.UI.HtmlTextWriter(strWriter); 43 dgExport = new System.Web.UI.WebControls.GridView(); 44 dgExport.DataSource = dtData.DefaultView; 45 dgExport.AllowPaging = false; 46 dgExport.DataBind(); 47 dgExport.RenderControl(htmlWriter); 48 curContext.Response.Write(strWriter.ToString()); 49 curContext.Response.End(); 50 } 51 52 }
使用实例(static 方法,可以被直接调用):
1 //ds是某DataSet对象,而后面是导出的Excel保存名字 2 ExportExcel.ExportByDataSet(ds, "PDLRFQ-" + DateTime.Now.ToString("yyyyMMdd"));