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 }
在网上找了一些方法但是最终整理成这个类,代码可能有冗余,尚在研究当中,同时也希望同志们指点一二。