alielie
2026-03-02 12e606635c42ea20f4b7c2bdda5204237a4b4c96
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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
using HMI.Core;
using HMI.Core.Util;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
 
namespace HMI.Util
{
    public class ExcelHelper
    {
        public static void ExportExcel<T>(string targetPath, IList<T> datas)
        {
            Type type = typeof(T);
            var properties = PropertyHelper.GetAtterProperty<T, ExcelColumnAttribute>(out var attrs);
            if (properties == null || properties.Count <= 0)
            {
                throw new Exception("No Attribute");
            }
            IWorkbook workbook = null;
            if (targetPath.EndsWith(".xlsx"))
            {
                workbook = new XSSFWorkbook();
            }
            else if (targetPath.EndsWith(".xls"))
            {
                workbook = new HSSFWorkbook();
            }
            workbook.CreateSheet("sheet1");////新建一个工作表
            ISheet SheetOne = workbook.GetSheet("Sheet1");
            IRow row1 = SheetOne.CreateRow(0);
            for (int i = 0; i < properties.Count; i++)
            {
                row1.CreateCell(i).SetCellValue(LangUtil.Get((attrs[i]).Name));
            }
 
            for (int i = 0; i < datas.Count(); i++)
            {
                IRow rowTemp = SheetOne.CreateRow(i + 1);
                for (int j = 0; j < properties.Count; j++)
                {
                    var attr = attrs[j];
                    var value = attr.IgnoreExport ? "" : properties[j].GetValue(datas[i]);
                    rowTemp.CreateCell(j).SetCellValue(value?.ToString());
                }
            }
 
            using (FileStream fs = new FileStream(targetPath, FileMode.OpenOrCreate))
            {
                workbook.Write(fs);
            }
        }
 
 
        public static List<T> ReadFromExcel<T>(string sourcePath)
        {
            Type type = typeof(T);
            var properties = PropertyHelper.GetAtterProperty<T, ExcelColumnAttribute>(out var attrs);
            if (properties == null || properties.Count <= 0)
            {
                throw new Exception("No Attribute");
            }
            Dictionary<string, PropertyInfo> dict = new Dictionary<string, PropertyInfo>();
            for (int i = 0; i < attrs.Count; i++)
            {
                dict.Add(LangUtil.Get(attrs[i].Name), properties[i]);
            }
            using (FileStream fileStream1 = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
            {
                IWorkbook workbook = null;
                if (sourcePath.EndsWith(".xls"))
                {
                    workbook = new HSSFWorkbook(fileStream1);
                }
                else
                {
                    workbook = new XSSFWorkbook(fileStream1);
                }
                int currentRow = 1;
                try
                {
                    ISheet sheet = workbook.GetSheetAt(0);
                    IRow titleRow = sheet.GetRow(0);
 
                    List<T> result = new List<T>();
                    IRow row;
                    for (currentRow = 1; currentRow < (sheet.LastRowNum + 1); currentRow++)
                    {
                        row = sheet.GetRow(currentRow);
                        if (row != null)
                        {
                            T obj = (T)Activator.CreateInstance(type);
                            bool isEmpty = true;
                            for (int j = 0; j < row.Count(); j++)
                            {
                                string title = titleRow.Cells[j].StringCellValue;
                                if (dict.ContainsKey(title))
                                {
                                    var cell = row.GetCell(j);
                                    if (cell == null || cell.CellType == CellType.Blank)
                                        continue;
                                    CellType ct = cell.CellType;
                                    object value = null;
                                    if (ct == CellType.String)
                                        value = row.GetCell(j).StringCellValue;
                                    else if (ct == CellType.Numeric)
                                        value = row.GetCell(j).NumericCellValue;
                                    else if (ct == CellType.Boolean)
                                        value = row.GetCell(j).BooleanCellValue;
                                    else
                                        value = row.GetCell(j).StringCellValue;
 
                                    var prop = dict[title];
                                    if (prop.PropertyType == typeof(string))
                                    {
                                        value = Convert.ToString(value);
                                    }
                                    else if (prop.PropertyType == typeof(double) || prop.PropertyType == typeof(double?))
                                    {
                                        value = Convert.ToDouble(value);
                                    }
                                    else if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(int?))
                                    {
                                        value = Convert.ToInt16(value);
                                    }
                                    else if (prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?))
                                    {
                                        value = Convert.ToBoolean(value);
                                    }
                                    else if (prop.PropertyType.IsEnum)
                                    {
                                        value = Enum.Parse(prop.PropertyType, value.ToString());
                                    }
                                    prop.SetValue(obj, value);
                                    isEmpty = false;
                                }
                            }
                            if (!isEmpty) result.Add(obj);
                        }
                    }
                    return result;
                }
                catch (Exception ex)
                {
                    throw new Exception($"第{currentRow}行解析错误:{ex.Message}", ex);
                }
                finally
                {
                    workbook.Close();
                }
            }
        }
    }
}