admin
2024-09-20 8b7b39172ee548ff303dbd73816cb7c1071f7887
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace CommonHelper.Format
{
    public class ModelHandler<T> where T : new()
    {
        /// <summary>
        /// 根据实体类得到表结构
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private static DataTable CreateData(T model)
        {
            DataTable dataTable = new DataTable(typeof(NPOI.SS.Formula.Functions.T).Name);
            foreach (System.Reflection.PropertyInfo propertyInfo in typeof(NPOI.SS.Formula.Functions.T).GetProperties())
            {
                dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
            }
 
            return dataTable;
        }
 
        /// <summary>
        /// 实体类转换成DataTable
        /// </summary>
        /// <param name="modelList">实体类列表</param>
        /// <returns></returns>
        public static DataTable FillDataTable(List<T> modelList)
        {
            if (modelList == null || modelList.Count == 0)
            {
                return null;
            }
 
            DataTable dt = CreateData(modelList[0]);
 
            foreach (T model in modelList)
            {
                DataRow dataRow = dt.NewRow();
                foreach (System.Reflection.PropertyInfo propertyInfo in typeof(NPOI.SS.Formula.Functions.T).GetProperties())
                {
                    dataRow[propertyInfo.Name] = propertyInfo.GetValue(model, null);
                }
 
                dt.Rows.Add(dataRow);
            }
 
            return dt;
        }
    }
}