list转换成DataTable类如下:
public static DataTable ToDataTable<T>(this IList<T> datas) { DataTable dt = new DataTable(); Type type = typeof(T); PropertyInfo[] properties = type.GetProperties(); List<KeyValuePair<PropertyInfo, ExportFieldAttribute>> propertyInfos = new List<KeyValuePair<PropertyInfo, ExportFieldAttribute>>(); //获取需要导出列信息 foreach (PropertyInfo propertyInfo in properties) { ExportFieldAttribute attribute = Attribute.GetCustomAttribute(propertyInfo, typeof(ExportFieldAttribute)) as ExportFieldAttribute; if (attribute != null) { propertyInfos.Add(new KeyValuePair<PropertyInfo, ExportFieldAttribute>(propertyInfo, attribute)); } } propertyInfos= propertyInfos.OrderBy(p => p.Value.Sort).ToList();//列排序 //添加列 propertyInfos.ForEach(p => { DataColumn dataColumn = new DataColumn(p.Key.Name, p.Key.PropertyType); dt.Columns.Add(dataColumn); } ); datas.ToList().ForEach(data => { DataRow dtRow = dt.NewRow(); foreach (PropertyInfo propertyInfo in propertyInfos.Select(p => p.Key)) { dtRow[propertyInfo.Name] = propertyInfo.GetValue(data, null); } dt.Rows.Add(dtRow); } ); ////填充数据 //foreach (T data in datas) //{ // DataRow dtRow = dt.NewRow(); // foreach (PropertyInfo propertyInfo in propertyInfos.Select(p=>p.Key)) // { // dtRow[propertyInfo.Name]=propertyInfo.GetValue(data, null); // } // dt.Rows.Add(dtRow); //} return dt; }