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. Java生鲜电商平台-SpringCloud微服务架构中网络请求性能优化与源码解析

    Java生鲜电商平台-SpringCloud微服务架构中网络请求性能优化与源码解析 说明:Java生鲜电商平台中,由于服务进行了拆分,很多的业务服务导致了请求的网络延迟与性能消耗,对应的这些问题,我们 ...

  2. 一则SQL优化案例

    原始sql: select CASE ) counts ,) else deadline end as deadline from t_product_credit) c group by sort ...

  3. 升鲜宝V2.0_生鲜配送行业,对生鲜配送行业的思考及对系统流程开发的反思_升鲜宝生鲜配送系统_15382353715_余东升

    升鲜宝V2.0_生鲜配送行业,对生鲜配送行业的思考及对系统流程开发的反思_升鲜宝生鲜配送系统_15382353715_余东升 -----生鲜配送行业现状及存在问题----- 1.  从业者整体素质偏低 ...

  4. Python单元测试工具doctest和unittest

    Python标准库包含两个测试工具. doctest:一个简单的模块,为检查文档而设计,但也适合用来编写单元测试. unittest:一个通用的测试框架. 一.使用doctest进行单元测试 创建文件 ...

  5. docker部署gitlab-ce

    简介 环境准备 centos7 docker 1.13.1 gitlab-ce 安装步骤 1.首先需要从docker镜像仓库当中获取gitlab-ce的最新镜像文件,由于我本机已经获取了该镜像,所以在 ...

  6. Web服务器—Apache

    Apache配置文件:httpd.conf文件 # 指定Apache的安装路径,此选项参数值在安装Apache时系统会自动把Apache的路径写入. ServerRoot "/www/ser ...

  7. Plugin org.apache.maven.plugins:maven-resources-plugin:2.6

    创建maven project时工程报错Plugin org.apache.maven.plugins:maven-resources-plugin:2.6 or one of its depende ...

  8. Python正则表达式中re.S作用

    re.S的作用: 不使用re.S时,则只在每一行内进行匹配,如果存在一行没有,就换下一行重新开始,使用re.S参数以后,正则表达式会将这个字符串看做整体,在整体中进行匹配 对比输出结果: import ...

  9. python函数内容

    在刚接触python的时候就有个疑问,什么是函数? python语言的函数和数学语言的函数有区别吗? 什么是函数 数学函数:给定一个数集A,假设其中的元素为x.现对A中的元素x施加对应法则f,记作f( ...

  10. while语句 break和continue

    1.whlie 循环 基本条件 :while 条件: 代码块(循环体) else: 当上面的条件为假的,才会执行 执行顺序: 判断条件是否为真,如果为真,执行循环体,然后判断条件,...直到循环条件为 ...