List<T>转DataTable
1 public static class DataConvertor
2 {
3 public static DataTable ToDataTable<T>(IEnumerable<T> data)
4 {
5 PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
6 var table = new DataTable();
7 foreach (PropertyDescriptor prop in properties)
8 table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
9 foreach (T item in data)
10 {
11 DataRow row = table.NewRow();
12 foreach (PropertyDescriptor prop in properties)
13 row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
14 table.Rows.Add(row);
15 }
16 return table;
17 }
18
19 public static DataTable ToDataTable(IRfcTable rfcTable)
20 {
21 DataTable table = new DataTable();
22 int liElement = 0;
23 for (liElement = 0; liElement <= rfcTable.ElementCount - 1; liElement++)
24 {
25 RfcElementMetadata metadata = rfcTable.GetElementMetadata(liElement);
26 table.Columns.Add(metadata.Name); //循环创建列
27 }
28 foreach (IRfcStructure dr in rfcTable) //循环table结构表
29 {
30 DataRow row = table.NewRow(); //创建新行
31 for (liElement = 0; liElement <= rfcTable.ElementCount - 1; liElement++)
32 {
33 RfcElementMetadata metadata = rfcTable.GetElementMetadata(liElement);
34 row[metadata.Name] = dr.GetString(metadata.Name).Trim();
35 }
36 table.Rows.Add(row);
37 }
38
39 return table;
40 }
41 }