netcore通用npoi导入excel

此篇博客介绍了如何使用C#编程语言通过IFormFile接口从Excel文件中读取数据,并转换为指定类型T的列表。它涵盖了异常处理和不同Excel文件格式的支持。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

        /// <summary>
        /// 获取excel文件内类容并转换成列表
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="file"></param>
        /// <returns></returns>
        public List<T> ImportExcel<T>(IFormFile file) where T : new()
        {
            List<T> _xlist = new List<T>();
            Type _xtype = typeof(T);
            var _xproperties = _xtype.GetProperties();
            try
            {
                string _xfile = Path.GetExtension(file.FileName).ToLower();
                MemoryStream _ms = new MemoryStream();
                file.CopyTo(_ms);
                _ms.Seek(0, SeekOrigin.Begin);
                IWorkbook _xbook;
                if (_xfile == ".xlsx")
                {
                    _xbook = new XSSFWorkbook(_ms);
                }
                else if (_xfile == ".xls")
                {
                    _xbook = new HSSFWorkbook(_ms);
                }
                else
                {
                    _xbook = null;
                }
                ISheet _xsheet = _xbook.GetSheetAt(0);

                int _xCountRow = _xsheet.LastRowNum + 1;//获取总行数

                if (_xCountRow - 1 == 0)
                {
                    return _xlist;
                }

                for (int i = 1; i < _xCountRow; i++)
                {
                    //获取第i行的数据
                    var _xrow = _xsheet.GetRow(i);
                    if (_xrow != null)
                    {
                        T xmodel = Activator.CreateInstance<T>();
                        //循环的验证单元格中的数据
                        for (int j = 0; j < _xproperties.Length; j++)
                        {
                            var _xproperty = _xproperties[j];
                            _xproperty.SetValue(xmodel, _xrow.GetCell(j) != null ? _xrow.GetCell(j).ToString() : string.Empty, null);
                        }
                        _xlist.Add(xmodel);
                    }
                }
                return _xlist;
            }
            catch (Exception e)
            {
                return _xlist;
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值