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;
        }
View Code

相关文章:

  • 2022-02-13
  • 2022-12-23
  • 2022-12-23
  • 2021-07-18
  • 2022-12-23
猜你喜欢
  • 2021-10-29
  • 2022-12-23
  • 2021-06-13
  • 2022-02-18
  • 2022-02-01
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案