public class ExcelHelper { //导出csv格式 public static void ExportToCSV(Page page, DataTable dt, string FileName) { System.Web.HttpResponse resp; resp = page.Response; resp.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); resp.HeaderEncoding = System.Text.Encoding.GetEncoding("GB2312"); resp.AddHeader("Content-Disposition", "attachment; filename=" +System.Web.HttpUtility.UrlEncode(FileName) + ".csv"); resp.ContentType = "application/ms-excel"; StringWriter sw = new StringWriter(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < dt.Columns.Count; i++) { sb.Append(dt.Columns[i].ColumnName); if (i != dt.Columns.Count - 1) { sb.Append(","); } } sw.WriteLine(sb.ToString()); foreach (DataRow dr in dt.Rows) { for (int i = 0; i < dt.Columns.Count; i++) { sw.Write(dr[i].ToString().Replace("<br/>", ",")); if (i != dt.Columns.Count - 1) { sw.Write(","); } } resp.Write(sw); sw.WriteLine(""); //sw.WriteLine(""); } // sw.Close(); // resp.Clear(); resp.Write(sw); resp.End(); } }
转载于:https://www.cnblogs.com/gotolovo/archive/2012/04/13/2445211.html