当前位置: 移动技术网 > IT编程>开发语言>.net > .NET Core 使用NPOI读取Excel返回泛型List集合

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

2019年11月09日  | 移动技术网IT编程  | 我要评论

新蜀山剑侠传修改器,道蒙官网,万壑松风书库

我是一名 asp.net 程序员,专注于 b/s 项目开发。累计文章阅读量超过一千万,我的博客主页地址:

 

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

首先先看效果图,如下:

 

 

模板

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

 

特性

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

public class columnattribute: attribute
    {
        public columnattribute(int index)
        {
            index = index;
        }
        public int index { get; set; }
    }

  

对象模型

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

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

代码如下:

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;
        }
    }

  

调用代码:

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();
        }

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

 

转载于:

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网