1 using System; 2 using System.Collections.Generic; 3 using System.IO; 4 using System.Linq; 5 using System.Reflection; 6 using System.Text; 7 using System.Threading.Tasks; 8 using System.Web; 9 10 namespace WebApp.Test 11 { 12 /// <summary> 13 /// List<T>導出類 14 /// </summary> 15 /// <typeparam name="T">列表中的元素類型</typeparam> 16 public class ExcelHelperForIList<T> 17 { 18 /// <summary> 19 /// 泛型導出Excel 20 /// </summary> 21 /// <param name="lt">要導出的List集合</param> 22 /// <param name="fileName">文件名</param> 23 /// <param name="fieldNames">導出的字段名()</param> 24 /// <param name="showNames">Excel標題行(需與FieldNames對應)</param> 25 /// <returns></returns> 26 public static string CreateAdvExcel(IList<T> lt, string fileName, string[] fieldNames, string[] showNames) 27 { 28 StringBuilder builder = new StringBuilder(); 29 Random rn = new Random(); 30 string name = fileName; 31 //經過反射獲得對象的屬性集合 32 System.Reflection.PropertyInfo[] myPropertyInfo = lt.First().GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance); 33 int i = 0, j; 34 for (int m = 0; m < fieldNames.Length; m++) 35 { 36 //遍歷屬性集合生成excel的表頭標題 37 for (i = 0, j = myPropertyInfo.Length; i < j; i++) 38 { 39 System.Reflection.PropertyInfo pi = myPropertyInfo[i]; 40 string headname = pi.Name;//單元格頭部 41 if (headname == fieldNames[m]) 42 { 43 builder.Append(showNames[m]); 44 builder.Append("\t"); 45 } 46 } 47 } 48 builder.Append("\n"); 49 //遍歷集合生成excel的行集數據 50 foreach (T item in lt) 51 { 52 if (lt == null) 53 { 54 continue; 55 } 56 for (int m = 0; m < fieldNames.Length; m++) 57 { 58 for (i = 0, j = myPropertyInfo.Length; i < j; i++) 59 { 60 PropertyInfo pi = myPropertyInfo[i]; 61 if (pi.Name == fieldNames[m]) 62 { 63 string str = string.Format("{0}", pi.GetValue(item, null)).Replace("\n", ""); 64 str = str.Replace(" ", " "); 65 if (str == "") 66 { 67 builder.Append("\t"); 68 } 69 else 70 { 71 builder.Append(str + "\t");//橫向跳到另外一個單元格 72 } 73 } 74 } 75 } 76 77 builder.Append("\n");//換行 78 } 79 StringWriter sw = new StringWriter(); 80 sw.WriteLine(builder); 81 sw.Close(); 82 83 HttpContext.Current.Response.Clear(); 84 // 指定返回的是一個不能被客戶端讀取的流,必須被下載 85 HttpContext.Current.Response.ContentType = "application/ms-excel"; 86 HttpContext.Current.Response.Charset = "UTF-8"; 87 HttpContext.Current.Response.Buffer = true; 88 HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312"); 89 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xls", name)); 90 HttpContext.Current.Response.Write(builder); 91 HttpContext.Current.Response.End(); 92 return builder.ToString(); 93 } 94 } 95 }
在網上找了一些方法可是最終整理成這個類,代碼可能有冗餘,尚在研究當中,同時也但願同志們指點一二。app