// 导出数据到Excel /// <param name="dataList"></param> /// <param name="fields"></param> /// <param name="headTexts"></param> /// <param name="title"></param> public static void ExportToExcel(System.Data.DataTable dataList, string[] fields, string[] headTexts, string title) { System.Web.UI.WebControls.GridView gvw = new System.Web.UI.WebControls.GridView(); int ColCount, i; //如果筛选的字段和对应的列头名称个数相对的情况下只导出指定的字段 if (fields.Length != 0 && fields.Length == headTexts.Length) { ColCount = fields.Length; gvw.AutoGenerateColumns = false; for (i = 0; i < ColCount; i++) { System.Web.UI.WebControls.BoundField bf = new System.Web.UI.WebControls.BoundField(); bf.DataField = fields[i]; bf.HeaderText = headTexts[i]; gvw.Columns.Add(bf); } } else { gvw.AutoGenerateColumns = true; } //SetStype(gvw); gvw.DataSource = dataList; gvw.DataBind(); ExportToExcel(gvw, title); } // 导出GridView中的数据到Excel /// <param name="gvw"></param> /// <param name="DataList"></param> private static void ExportToExcel(System.Web.UI.WebControls.GridView gvw, string title) { string fileName; HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.ClearContent(); HttpContext.Current.Response.ClearHeaders(); fileName = string.Format("{0:yyyy-MM-dd_HH_mm}.xls", DateTime.Now); HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName); HttpContext.Current.Response.ContentType = "application/vnd.ms-excel"; HttpContext.Current.Response.ContentEncoding = Encoding.UTF8; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">"); StringWriter tw = new System.IO.StringWriter(); HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw); gvw.RenderControl(hw); if (!string.IsNullOrEmpty(title)) { HttpContext.Current.Response.Write("<b><center><font size=3 face=Verdana color=#0000FF>" + title + "</font></center></b>"); } HttpContext.Current.Response.Write(tw.ToString()); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Close(); //HttpContext.Current.Response.End(); gvw.Dispose(); tw.Dispose(); hw.Dispose(); gvw = null; tw = null; hw = null; }
转载于:https://www.cnblogs.com/Alwayswantmore/p/Export_1.html
