使用using System.IO;
1 /// <summary> 2 /// 导出Excel文件,并自定义文件名 3 /// </summary> 4 public static void DataTable3Excel(System.Data.DataTable dtData, String FileName) 5 { 6 GridView dgExport = null; 7 HttpContext curContext = HttpContext.Current; 8 StringWriter strWriter = null; 9 HtmlTextWriter htmlWriter = null; 10 11 if (dtData != null) 12 { 13 HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); 14 curContext.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8) + ".xls"); 15 curContext.Response.ContentType = "application nd.ms-excel"; 16 curContext.Response.ContentEncoding = System.Text.Encoding.UTF8; 17 curContext.Response.Charset = "GB2312"; 18 strWriter = new StringWriter(); 19 htmlWriter = new HtmlTextWriter(strWriter); 20 dgExport = new GridView(); 21 dgExport.DataSource = dtData.DefaultView; 22 dgExport.AllowPaging = false; 23 dgExport.DataBind(); 24 dgExport.RenderControl(htmlWriter); 25 curContext.Response.Write(strWriter.ToString()); 26 curContext.Response.End(); 27 } 28 }
ToDataTableClass类
1 public static class ToDataTableClass 2 { 3 /// <summary> 4 /// Convert a List{T} to a DataTable. 5 /// </summary> 6 public static DataTable ToDataTable<T>(List<T> items) 7 { 8 var tb = new DataTable(typeof(T).Name); 9 10 PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance); 11 12 foreach (PropertyInfo prop in props) 13 { 14 Type t = GetCoreType(prop.PropertyType); 15 tb.Columns.Add(prop.Name, t); 16 } 17 18 foreach (T item in items) 19 { 20 var values = new object[props.Length]; 21 22 for (int i = 0; i < props.Length; i++) 23 { 24 values[i] = props[i].GetValue(item, null); 25 } 26 27 tb.Rows.Add(values); 28 } 29 30 return tb; 31 } 32 /// <summary> 33 /// Determine of specified type is nullable 34 /// </summary> 35 public static bool IsNullable(Type t) 36 { 37 return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)); 38 } 39 /// <summary> 40 /// Return underlying type if type is Nullable otherwise return the type 41 /// </summary> 42 public static Type GetCoreType(Type t) 43 { 44 if (t != null && IsNullable(t)) 45 { 46 if (!t.IsValueType) 47 { 48 return t; 49 } 50 else 51 { 52 return Nullable.GetUnderlyingType(t); 53 } 54 } 55 else 56 { 57 return t; 58 } 59 } 60 }
controller:
1 public ActionResult GetData(string keyValue,string filename) 2 { 3 4 System.Data.DataTable __dtData = _userExamApp.GetData(keyValue); 5 ExcelHelper.DataTable3Excel(__dtData, filename + "的试卷记录"); 6 7 }
app:
1 public DataTable GetData(string keyValue) 2 { 3 DataTable __mydt = ToDataTableClass.ToDataTable(Get(keyValue)); 4 __mydt.Columns.Remove("A1"); 5 __mydt.Columns.Remove("A2"); 6 __mydt.Columns["A3"].ColumnName = "A3Name"; 7 __mydt.Columns["A4"].ColumnName = "A4Name"; 9 10 return __mydt; 11 }