最近在做Excel导出,看到了这个方法,虽不是自己写的,但值得收藏,但是忘记从那摘抄的,没写原文作者看到望见谅!
1 #region 导出Excel 2 /// <summary> 3 /// list 转换Datatable 4 /// </summary> 5 /// <param name="ResList"></param> 6 /// <returns></returns> 7 public DataTable DataOut(List<Excel> ResList) 8 { 9 10 DataTable TempDT = new DataTable(); 11 System.Reflection.PropertyInfo[] p = ResList[0].GetType().GetProperties(); 12 foreach (System.Reflection.PropertyInfo pi in p) 13 { 14 TempDT.Columns.Add(pi.Name); 15 } 16 for (int i = 0; i < ResList.Count; i++) 17 { 18 ArrayList TempList = new ArrayList(); 19 //将IList中的一条记录写入ArrayList 20 foreach (System.Reflection.PropertyInfo pi in p) 21 { 22 object oo = pi.GetValue(ResList[i], null); 23 TempList.Add(oo); 24 } 25 26 object[] itm = new object[p.Length]; 27 //遍历ArrayList向object[]里放数据 28 for (int j = 0; j < TempList.Count; j++) 29 { 30 itm.SetValue(TempList[j], j); 31 } 32 //将object[]的内容放入DataTable 33 TempDT.LoadDataRow(itm, true); 34 } 35 //返回DataTable 36 return TempDT; 37 }