.NET Core 使用NPOI读取Excel返回泛型List集合

我是一名 ASP.NET 程序员,专注于 B/S 项目开发。累计文章阅读量超过一千万,我的博客主页地址:https://www.itsvse.com/blog_xzz.html

 

网上有很多关于npoi读取excel表格的例子,很多都是返回一个Datatable的对象,但是我需要的是一个list集合,这里就需要把Datatable转成自己需要的List集合,所以,我封装了一个方法,传入class对象就能返回相应的list对象。

首先先看效果图,如下:

 

 

模板

一共有4列,有很多行,其中只有2行有数据,如下图:

 

特性

首先,定义一个特性,意义是对象的属性对应表格的哪一列,代码如下:

1
2
3
4
5
6
7
8
public class ColumnAttribute: Attribute
    {
        public ColumnAttribute(int index)
        {
            Index = index;
        }
        public int Index { get; set; }
    }

  

对象模型

将表格数据读取出来,转换成相应的对象集合,在对象的属性标注上面定义的特性,代码如下:

1
2
3
4
5
6
7
8
9
10
11
public class TestModel
    {
        [Column(0)]
        public string Name { get; set; }
        [Column(1)]
        public string Url { get; set; }
        [Column(2)]
        public string Date { get; set; }
        [Column(3)]
        public string Remark { get; set; }
    }

  

封装的方法

nuget安装npoi:

Install-Package DotNetCore.NPOI -Version 1.2.2

代码如下:

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
public class ExcelHelper
    {
        /// <summary>
        /// 读取excel转换成list集合
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="stream">文件流</param>
        /// <param name="startIndex">从第几行开始读取</param>
        /// <param name="sheetIndex">读取第几个sheet</param>
        /// <returns></returns>
        public static IList<T> GetList<T>(Stream stream, int startIndex, int sheetIndex = 0)
            where T : class
        {
            IList<T> ts = new List<T>();
            try
            {
                IWorkbook workbook = WorkbookFactory.Create(stream);
                var sheet = workbook.GetSheetAt(sheetIndex);
                if (sheet != null)
                {
                    IRow firstRow = sheet.GetRow(0);
                    //一行最后一个cell的编号 即总的列数
                    int cellCount = firstRow.LastCellNum;
                    //最后一列的标号
                    int rowCount = sheet.LastRowNum;
                    for (int i = startIndex; i <= rowCount; ++i)
                    {
                        //获取行的数据
                        IRow row = sheet.GetRow(i);
                        if (row == null) continue; //没有数据的行默认是null       
                        {
                            T model = Activator.CreateInstance<T>();
                            for (int j = row.FirstCellNum; j < cellCount; ++j)
                            {
                                if (row.GetCell(j) != null)
                                {
                                    var rowTemp = row.GetCell(j);
                                    string value = null;
                                    if (rowTemp.CellType == CellType.Numeric)
                                    {
                                        short format = rowTemp.CellStyle.DataFormat;
                                        if (format == 14 || format == 31 || format == 57 || format == 58 || format == 20)
                                            value = rowTemp.DateCellValue.ToString("yyyy-MM-dd");
                                        else
                                            value = rowTemp.NumericCellValue.ToString();
                                    }
                                    else
                                        value = rowTemp.ToString();
                                    //赋值
                                    foreach (System.Reflection.PropertyInfo item in typeof(T).GetProperties())
                                    {
                                        var column = item.GetCustomAttributes(true).First(x => x is ColumnAttribute) as ColumnAttribute;
                                        if (column.Index == j)
                                        {
                                            item.SetValue(model, value);
                                            break;
                                        }
                                    }
                                }
                            }
                            ts.Add(model);
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                if (stream != null) stream.Close();
            }
            return ts;
        }
    }

  

调用代码:

1
2
3
4
5
6
7
8
9
10
static void Main(string[] args)
        {
 
            FileStream fs = new FileStream(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/test.xlsx", FileMode.Open, FileAccess.Read);
            var temp = ExcelHelper.GetList<TestModel>(fs, 3);
            var json1 = Newtonsoft.Json.JsonConvert.SerializeObject(temp.Where(x => !string.IsNullOrWhiteSpace(x.Name)).ToList());
            Console.WriteLine(json1);
            Console.WriteLine("ok");
            Console.ReadKey();
        }

  最后,就出现了文章最开始的效果图。

 

转载于:https://down.itsvse.com/k/0tmhog.html

posted @   _小渣渣  阅读(2565)  评论(6编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· DeepSeek在M芯片Mac上本地化部署
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
点击右上角即可分享
微信分享提示