標籤:style blog http color io os ar for 資料
最近在做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中的一條記錄寫入ArrayList20 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[]的內容放入DataTable33 TempDT.LoadDataRow(itm, true);34 }35 //返回DataTable36 return TempDT;37 }
View Code
C# List 轉Datatable