netcore通用npoi导入excel

netcore通用npoi导入excel,第1张

netcore通用npoi导入excel

        ///


        /// 获取excel文件内类容并转换成列表
        ///

        ///
        ///
        ///
        public List importExcel(IFormFile file) where T : new()
        {
            List _xlist = new List();
            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();
                        //循环的验证单元格中的数据
                        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;
            }
        }

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5660730.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存