1.仅适用于规则Excel:表头和数据一一对应

2.涉及到Excel转换为集合对象的部分代码,完整npoi帮助类点击查看

        /// <summary>
/// 默认把excel第一个sheet中的数据转换为对象集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="filePath">文件路径</param>
/// <param name="sheetIndex">数据所在sheet索引:默认第一个sheet</param>
/// <param name="originIndex">数据开始行:表头行索引</param>
/// <returns></returns>
public static List<T> ConvertExcelToList<T>(T entity, string filePath, int sheetIndex = , int originIndex = )
where T : class, new()
{
var stream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
using (stream)
{
return ConvertExcelToList(entity, filePath, stream, sheetIndex, originIndex);
} } /// <summary>
/// 把excel转换为对象集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="filePath">文件路径</param>
/// <param name="stream">文件流</param>
/// <param name="sheetIndex">数据所在sheet索引:默认第一个sheet</param>
/// <param name="originIndex">数据开始行:表头行索引</param>
/// <returns></returns>
public static List<T> ConvertExcelToList<T>(T entity, string filePath, Stream stream, int sheetIndex = , int originIndex = )
where T : class, new()
{
// 结果集合
var list = new List<T>(); // 获取特性和属性的关系字典
Dictionary<string, string> propertyDictionary = GetPropertyDictionary(entity); var isExcel2007 = filePath.IsExcel2007();
var workBook = stream.GetWorkbook(isExcel2007);
// 获得数据所在sheet对象
var sheet = workBook.GetSheetAt(sheetIndex);
// 获取表头和所在索引的关系字典
Dictionary<string, int> headerDictionary = GetHeaderDictionary(originIndex, propertyDictionary, sheet); // 两个字典对象,只有一个为空,则return
if (!propertyDictionary.Any() || !headerDictionary.Any())
{
return list;
} // 生成结果集合
BuilderResultList(originIndex, list, propertyDictionary, sheet, headerDictionary);
return list;
} /// <summary>
/// 生成结果集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="originIndex">数据开始行:表头行索引</param>
/// <param name="list">结果集合</param>
/// <param name="propertyDictionary">特性和属性的关系字典:属性字典</param>
/// <param name="sheet">数据所在sheet对象</param>
/// <param name="headerDictionary">表头和所在索引的关系字典:表头字典</param>
private static void BuilderResultList<T>(int originIndex, List<T> list, Dictionary<string, string> propertyDictionary, ISheet sheet, Dictionary<string, int> headerDictionary) where T : class, new()
{
#region 通过反射,绑定参数 // 从表头行下一行开始循环,直到最后一行
for (int rowIndex = originIndex + ; rowIndex <= sheet.LastRowNum; rowIndex++)
{
T newEntity = new T();
var newEntityType = newEntity.GetType();
var itemRow = sheet.GetRow(rowIndex); // 循环表头字典
foreach (var itemKey in headerDictionary.Keys)
{
// 得到先对应的表头列所在列索引
var columnIndex = headerDictionary[itemKey];
// 把格式转换为utf-8
var itemCellValue = itemRow.GetValue(columnIndex).FormatUtf8String(); // 根据表头值,从 属性字典 中获得 属性值 名
var propertyName = propertyDictionary[itemKey];
newEntityType.GetProperty(propertyName).SetValue(newEntity, itemCellValue);
}
list.Add(newEntity);
} #endregion
} /// <summary>
/// 获取表头和所在索引的关系字典
/// </summary>
/// <param name="originIndex">数据开始行:表头行索引</param>
/// <param name="propertyDictionary">特性和属性的关系字典:属性字典</param>
/// <param name="sheet">数据所在sheet对象</param>
/// <returns></returns>
private static Dictionary<string, int> GetHeaderDictionary(int originIndex, Dictionary<string, string> propertyDictionary, ISheet sheet)
{
var headerDictionary = new Dictionary<string, int>(); #region 获取表头和所在索引的关系字典 // 获得表头所在row对象
var itemRow = sheet.GetRow(originIndex);
// 记录表头行,表头和所在索引的关系,存入字典,暂不考虑表头相同情况
headerDictionary = new Dictionary<string, int>();
// 可能会存在无限列情况,设置最大列为200
var cellTotal = itemRow.Cells.Count() > ? : itemRow.Cells.Count();
for (int columnIndex = ; columnIndex < cellTotal; columnIndex++)
{
// 把格式转换为utf-8
var itemCellValue = itemRow.GetValue(columnIndex).FormatUtf8String();
// itemCellValue补等于空 且 不在headerDictionary中 且 在propertyDictionary中
if (!itemCellValue.IsNullOrWhiteSpace() && !headerDictionary.ContainsKey(itemCellValue) && propertyDictionary.ContainsKey(itemCellValue))
{
headerDictionary.Add(itemCellValue, columnIndex);
}
} #endregion return headerDictionary;
} /// <summary>
/// 获取特性和属性的关系字典
/// </summary>
/// <param name="PropertyArr"></param>
/// <returns></returns>
private static Dictionary<string, string> GetPropertyDictionary<T>(T entity)
{
// 获取type
var userType = typeof(T);
// 获取类中所有公共属性集合
var propertyArr = userType.GetProperties(); #region 获取特性和属性的关系字典 // 属性字典,保存别名和属性的对应关系
// key:别名,特性中的值
// value:属性名,类中的属性
var propertyDictionary = new Dictionary<string, string>();
foreach (var itemProperty in propertyArr)
{
// 获取属性上存在AliasAttribute的数组
var customAttributesArr = itemProperty.GetCustomAttributes(typeof(AliasAttribute), true);
// 存在该特性
if (customAttributesArr.Any())
{
var first = (AliasAttribute)customAttributesArr.FirstOrDefault();
if (!propertyDictionary.ContainsKey(first.Name))
{
propertyDictionary.Add(first.Name, itemProperty.Name);
}
}
} #endregion
return propertyDictionary;
}

3.调用测试

            var path = @"C:\导入文件.xlsx";
var result = NpoiHelper.ConvertExcelToList(new UserDto(), path); Assert.IsTrue(result.Any());

NET Excel转换为集合对象的更多相关文章

  1. JAVA中json转换为集合(对象)之间的相互转换

    字符串转换为json对象: String strResult = RestUtil.getRestContent(url+"/service/peccancy/myOrderList&quo ...

  2. NPOI读取Excel到集合对象

    之前做过的项目中有个需要读取Excel文件内容的需求,因此使用NPOI实现,写下以下代码,这个只是一个代码段,还有很多地方需要优化,希望能对大家有所帮助 public static IList< ...

  3. 实体模型集合对象转换为VO对象集合

    例如: 数据库中查出来的数据为 List<RptDayMonthTarget> List<RptDayMonthTarget> list = targetService.sel ...

  4. wpf 导出Excel Wpf Button 样式 wpf简单进度条 List泛型集合对象排序 C#集合

    wpf 导出Excel   1 private void Button_Click_1(object sender, RoutedEventArgs e) 2 { 3 4 ExportDataGrid ...

  5. JSon_零基础_004_将Set集合对象转换为JSon格式的对象字符串,返回给界面

    将Set集合对象转换为JSon格式的对象字符串,返回给界面 需要导入的jar包: 编写:servlet: package com.west.webcourse.servlet; import java ...

  6. JSon_零基础_003_将Map集合对象转换为JSon格式的对象字符串,返回给界面

    将Map集合对象转换为JSon格式的对象字符串,返回给界面 需导入的jar包: 编写servlet: package com.west.webcourse.servlet; import java.i ...

  7. java 数据类型:Stream流 对象转换为集合collect(Collectors.toList()) ;常用方法count,limit,skip,concat,max,min

    集合对象.stream() 获取流对象,对元素批处理(不改变原集合) 集合元素循环除了用for循环取出,还有更优雅的方式.forEach 示例List集合获取Stream对象进行元素批处理 impor ...

  8. 集合学习之"将集合对象List<Product>转换为Map"

    将集合对象List<Product>转换为Map key = Product对象的sku value =Product对象 1 List<Product> products = ...

  9. JavaScript操作JSON的方法总结,JSON字符串转换为JSON对象

    JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,是理想的数据交换格式.同时,JSON是 JavaScript 原生格式,这意 ...

随机推荐

  1. MySQL问题记录——导入导出权限设置

    MySQL问题记录——导入导出权限设置 摘要:本文主要记录了在使用MySQL的过程中导入导出权限设置时遇到的问题以及解决方案. 相关日志 [Note] --secure-file-priv is se ...

  2. AQS(抽象队列同步器)

    AQS(全称为AbstractQueuedSynchronizer),即抽象队列同步器,它维护了一个volatile int state(代表共享资源)和一个FIFO线程等待队列. state的访问方 ...

  3. CSS边框使用-基础

    前端开发工作中经常会碰到奇形怪状的图形,当然也少不了UI设计童鞋的脑洞和创意啦,初级的开发人员可能会选择使用图片做背景加上位置属性实现,不过很多时候,CSS能实现的就不要再动用PS等工具了,时间宝贵, ...

  4. [b0034] python 归纳 (十九)_线程同步_条件变量

    代码: # -*- coding: utf-8 -*- """ 学习线程同步,使用条件变量 逻辑: 生产消费者模型 一个有3个大小的产品库,一个生产者负责生产,一个消费者 ...

  5. idea中git标签(tag)的创建与使用

    1.什么是标签 通常,发布一个版本时,会在版本库中打一个标签(tag),这样,就唯一确定了打标签时刻的版本.将来无论什么时候,取某个标签的版本,就是把那个打标签的时刻的历史版本取出来. 所以,标签也是 ...

  6. springboot 使用 jedis 连接 Redis 数据库

    1. 在 pom.xml 配置文件中添加依赖 <!-- redis 依赖 --> <dependency> <groupId>org.springframework ...

  7. centos安装php5、卸载php、安装php7

    这篇文章主要介绍了centos安装php5.卸载php.安装php7 ,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下 首先安装php5很简单 yum install php 然后如果不 ...

  8. 5-6 可视化库Seaborn-Facetgrid使用和绘制多变量

      基本工作流程是FacetGrid使用数据集和用于构造网格的变量初始化对象.然后,可以通过调用FacetGrid.map()或将一个或多个绘图函数应用于每个子集 FacetGrid.map_data ...

  9. .Net Core使用Swagger来对接口文档化

    参考文档来源:https://www.cnblogs.com/yilezhu/p/9241261.html 官方地址 https://swagger.io/ 代码即接口文档,接口文档即代码 使用.ne ...

  10. 用maven运行指定java类main方法

    mvn exec:java -Dexec.mainClass="com.java2s.ide.App"