heyuntao
2023-05-04 fbd6a11a99051f425640bf352842f4a0ecaa7a4d
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
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Text;
 
namespace CommonUtil.Excel
{
    /// <summary>
    /// Excel工具类
    /// </summary>
    public class ExcelUtil
    {
        /// <summary>
        /// 导出excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entitys">数据源</param>
        /// <param name="title">导出的列名</param>
        /// <param name="listcolum">导出的列</param>
        /// <returns></returns>
        public static byte[] Output<T>(List<T> entitys, string[] title, List<string> listcolum)
        {
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet("sheet");
            ISheet sheet1 = workbook.CreateSheet("sheet1");
            ISheet sheet2 = workbook.CreateSheet("sheet2");
            IRow Title = null;
            IRow rows = null;
            Type entityType = entitys[0].GetType();
            PropertyInfo[] entityProperties = entityType.GetProperties();
 
            try
            {
                for (int i = 0; i <= entitys.Count; i++)
                {
                    if (i == 0)
                    {
                        Title = sheet.CreateRow(0);
                        for (int k = 1; k < title.Length + 1; k++)
                        {
                            Title.CreateCell(0).SetCellValue("序号");
                            Title.CreateCell(k).SetCellValue(title[k - 1]);
                        }
 
                        continue;
                    }
                    else
                    {
                        rows = sheet.CreateRow(i);
                        object entity = entitys[i - 1];
                        for (int c = 0; c <= listcolum.Count - 1; c++)
                        {
                            for (int j = 1; j <= entityProperties.Length; j++)
                            {
                                if (entityProperties[j - 1].Name == listcolum[c])
                                {
                                    var dem = entityProperties[j - 1].GetValue(entity);
                                    rows.CreateCell(0).SetCellValue(i);
 
                                    rows.CreateCell(c + 1).SetCellValue(dem.ToString());
                                }
                            }
 
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }
 
            byte[] buffer = new byte[1024 * 2];
            using (MemoryStream ms = new MemoryStream())
            {
                workbook.Write(ms);
                buffer = ms.GetBuffer();
            }
            return buffer;
        }
 
        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ms">数据流</param>
        /// <returns></returns>
        public static List<T> InputExcel<T>(Stream ms) where T : new()
        {
            List<T> list = new List<T> { };
            ms.Seek(0, SeekOrigin.Begin);
            IWorkbook workbook = null;
            try
            {
                //xlsx
                workbook = new XSSFWorkbook(ms);
            }
            catch (Exception)
            {
                //xls
                workbook = new HSSFWorkbook(ms);
            }
 
 
 
            ISheet sheet = workbook.GetSheetAt(0);
            IRow cellNum = sheet.GetRow(0);
            var propertys = typeof(T).GetProperties();
            string value = null;
            int num = cellNum.LastCellNum;
 
            for (int i = 0; i <= sheet.LastRowNum; i++)
            {
                IRow row = sheet.GetRow(i);
                if (row == null)
                {
                    continue;
                }
                var obj = new T();
                for (int j = 0; j < num; j++)
                {
                    //当输出类型属性个数小于文件列数时,跳出
                    if (propertys.Length - 1 < j)
                    {
                        break;
                    }
                    if (row.GetCell(j) == null)
                    {
                        continue;
                    }
                    value = row.GetCell(j).ToString();
                    string str = (propertys[j].PropertyType).FullName;
                    if (str == "System.String")
                    {
                        propertys[j].SetValue(obj, value, null);
                    }
                    else if (str == "System.DateTime")
                    {
                        DateTime pdt = Convert.ToDateTime(value, CultureInfo.InvariantCulture);
                        propertys[j].SetValue(obj, pdt, null);
                    }
                    else if (str == "System.Boolean")
                    {
                        bool pb = Convert.ToBoolean(value);
                        propertys[j].SetValue(obj, pb, null);
                    }
                    else if (str == "System.Int16")
                    {
                        short pi16 = Convert.ToInt16(value);
                        propertys[j].SetValue(obj, pi16, null);
                    }
                    else if (str == "System.Int32")
                    {
                        int pi32 = Convert.ToInt32(value);
                        propertys[j].SetValue(obj, pi32, null);
                    }
                    else if (str == "System.Int64")
                    {
                        long pi64 = Convert.ToInt64(value);
                        propertys[j].SetValue(obj, pi64, null);
                    }
                    else if (str == "System.Byte")
                    {
                        byte pb = Convert.ToByte(value);
                        propertys[j].SetValue(obj, pb, null);
                    }
                    else
                    {
                        propertys[j].SetValue(obj, null, null);
                    }
                }
 
                list.Add(obj);
            }
 
            return list;
        }
 
        /// <summary>
        /// 导入Excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ms"></param>
        /// <param name="hasHeader"></param>
        /// <returns></returns>
        public static List<T> InputExcel<T>(Stream ms, bool hasHeader = false) where T : new()
        {
            List<T> list = new List<T> { };
            ms.Seek(0, SeekOrigin.Begin);
            IWorkbook workbook = null;
            try
            {
                //xlsx
                workbook = new XSSFWorkbook(ms);
            }
            catch (Exception)
            {
                //xls
                workbook = new HSSFWorkbook(ms);
            }
 
 
 
            ISheet sheet = workbook.GetSheetAt(0);
            IRow cellNum = sheet.GetRow(0);
            var propertys = typeof(T).GetProperties();
            string value = null;
            int num = cellNum.LastCellNum;
 
            for (int i = 0; i <= sheet.LastRowNum; i++)
            {
                if (hasHeader && i == 0)
                {
                    continue;
                }
 
                IRow row = sheet.GetRow(i);
                if (row == null || row.Cells.Count != num)
                {
                    continue;
                }
                var obj = new T();
                for (int j = 0; j < num; j++)
                {
                    //当输出类型属性个数小于文件列数时,跳出
                    if (propertys.Length - 1 < j)
                    {
                        break;
                    }
 
                    value = row.GetCell(j).ToString();
                    string str = (propertys[j].PropertyType).FullName;
                    if (str == "System.String")
                    {
                        propertys[j].SetValue(obj, value, null);
                    }
                    else if (str == "System.DateTime")
                    {
                        try
                        {
                            propertys[j].SetValue(obj, row.GetCell(j).DateCellValue, null);
                        }
                        catch (Exception e)
                        {
                            throw e;
                        }
 
                    }
                    else if (str == "System.Boolean")
                    {
                        bool pb = Convert.ToBoolean(value);
                        propertys[j].SetValue(obj, pb, null);
                    }
                    else if (str == "System.Int16")
                    {
                        short pi16 = Convert.ToInt16(value);
                        propertys[j].SetValue(obj, pi16, null);
                    }
                    else if (str == "System.Int32")
                    {
                        int pi32 = Convert.ToInt32(value);
                        propertys[j].SetValue(obj, pi32, null);
                    }
                    else if (str == "System.Int64")
                    {
                        long pi64 = Convert.ToInt64(value);
                        propertys[j].SetValue(obj, pi64, null);
                    }
                    else if (str == "System.Byte")
                    {
                        byte pb = Convert.ToByte(value);
                        propertys[j].SetValue(obj, pb, null);
                    }
                    else
                    {
                        propertys[j].SetValue(obj, null, null);
                    }
                }
 
                list.Add(obj);
            }
 
            return list;
        }
 
        /// <summary>
        /// 导入csv
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="ms">数据流</param>
        /// <returns></returns>
        public static List<T> InputCSV<T>(Stream ms) where T : new()
        {
            List<T> list = new List<T> { };
            ms.Seek(0, SeekOrigin.Begin);
 
            //Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
            StreamReader sr = new StreamReader(ms, Encoding.GetEncoding("GB2312"));
            var propertys = typeof(T).GetProperties();
            while (!sr.EndOfStream)
            {
                string[] values = sr.ReadLine().Split(',');
                var obj = new T();
                for (int i = 0; i < values.Length; i++)
                {
                    //当输出类型属性个数小于文件列数时,跳出
                    if (propertys.Length - 1 < i)
                    {
                        break;
                    }
                    string value = values[i].ToString();
                    string str = (propertys[i].PropertyType).FullName;
                    if (str == "System.String")
                    {
                        propertys[i].SetValue(obj, value, null);
                    }
                    else if (str == "System.DateTime")
                    {
                        DateTime pdt = Convert.ToDateTime(value, CultureInfo.InvariantCulture);
                        propertys[i].SetValue(obj, pdt, null);
                    }
                    else if (str == "System.Boolean")
                    {
                        bool pb = Convert.ToBoolean(value);
                        propertys[i].SetValue(obj, pb, null);
                    }
                    else if (str == "System.Int16")
                    {
                        short pi16 = Convert.ToInt16(value);
                        propertys[i].SetValue(obj, pi16, null);
                    }
                    else if (str == "System.Int32")
                    {
                        int pi32 = Convert.ToInt32(value);
                        propertys[i].SetValue(obj, pi32, null);
                    }
                    else if (str == "System.Int64")
                    {
                        long pi64 = Convert.ToInt64(value);
                        propertys[i].SetValue(obj, pi64, null);
                    }
                    else if (str == "System.Byte")
                    {
                        byte pb = Convert.ToByte(value);
                        propertys[i].SetValue(obj, pb, null);
                    }
                    else
                    {
                        propertys[i].SetValue(obj, null, null);
                    }
                }
                list.Add(obj);
            }
            return list;
        }
    }
}