1 /// <summary> 2 /// List集合转DataTable 3 /// </summary> 4 /// <typeparam name="T">实体类型</typeparam> 5 /// <param name="list">传入集合</param> 6 /// <param name="isStoreDB">是否存入数据库DateTime字段,date时间范围没事,取出展示不用设置TRUE</param> 7 /// <returns>返回datatable结果</returns> 8 public static DataTable ListToTable<T>(List<T> list, bool isStoreDB = true) 9 { 10 Type tp = typeof(T); 11 PropertyInfo[] proInfos = tp.GetProperties(); 12 DataTable dt = new DataTable(); 13 foreach (var item in proInfos) 14 { 15 dt.Columns.Add(item.Name, item.PropertyType); //添加列明及对应类型 16 } 17 foreach (var item in list) 18 { 19 DataRow dr = dt.NewRow(); 20 foreach (var proInfo in proInfos) 21 { 22 object obj = proInfo.GetValue(item); 23 if (obj == null) 24 { 25 continue; 26 } 27 //if (obj != null) 28 // { 29 if (isStoreDB && proInfo.PropertyType == typeof(DateTime) && Convert.ToDateTime(obj) < Convert.ToDateTime("1753-01-01")) 30 { 31 continue; 32 } 33 // dr[proInfo.Name] = proInfo.GetValue(item); 34 dr[proInfo.Name] = obj; 35 // } 36 } 37 dt.Rows.Add(dr); 38 } 39 return dt; 40 }