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; }
属性类如下:
public class ExportFieldAttribute : Attribute { public ExportFieldAttribute() { } public ExportFieldAttribute(int sort) { Sort = sort; } public int Sort { get; set; }//排序 }
属性标记的类如下:
public class DiscardStatics { private string _sn; [ExportFieldAttribute(Sort=2)] public string Sn { get { return _sn; } set { _sn = value; } } private string _propertyName; [ExportFieldAttribute(3)] public string PropertyName { get { return _propertyName; } set { _propertyName = value; } } private string aa { get; set; } private string _type; [ExportFieldAttribute(5)] public string Type { get { return _type; } set { _type = value; } } private DateTime _discardTime; [ExportFieldAttribute(4)] public DateTime DiscardTime { get { return _discardTime; } set { _discardTime = value; } } private double residuals; [ExportFieldAttribute(1)] public double Residuals { get { return residuals; } set { residuals = value; } } private string _propertyId; public string PropertyId { get { return _propertyId; } set { _propertyId = value; } } private string _brand; public string Brand { get { return _brand; } set { _brand = value; } } private string _supplier; public string Supplier { get { return _supplier; } set { _supplier = value; } } private string _contactInfo; public string ContactInfo { get { return _contactInfo; } set { _contactInfo = value; } } private string _childPtyId; public string ChildPtyId { get { return _childPtyId; } set { _childPtyId = value; } } private string _childPtyName; public string ChildPtyName { get { return _childPtyName; } set { _childPtyName = value; } } }