NET Excel转换为集合对象
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转换为集合对象的更多相关文章
- JAVA中json转换为集合(对象)之间的相互转换
字符串转换为json对象: String strResult = RestUtil.getRestContent(url+"/service/peccancy/myOrderList&quo ...
- NPOI读取Excel到集合对象
之前做过的项目中有个需要读取Excel文件内容的需求,因此使用NPOI实现,写下以下代码,这个只是一个代码段,还有很多地方需要优化,希望能对大家有所帮助 public static IList< ...
- 实体模型集合对象转换为VO对象集合
例如: 数据库中查出来的数据为 List<RptDayMonthTarget> List<RptDayMonthTarget> list = targetService.sel ...
- wpf 导出Excel Wpf Button 样式 wpf简单进度条 List泛型集合对象排序 C#集合
wpf 导出Excel 1 private void Button_Click_1(object sender, RoutedEventArgs e) 2 { 3 4 ExportDataGrid ...
- JSon_零基础_004_将Set集合对象转换为JSon格式的对象字符串,返回给界面
将Set集合对象转换为JSon格式的对象字符串,返回给界面 需要导入的jar包: 编写:servlet: package com.west.webcourse.servlet; import java ...
- JSon_零基础_003_将Map集合对象转换为JSon格式的对象字符串,返回给界面
将Map集合对象转换为JSon格式的对象字符串,返回给界面 需导入的jar包: 编写servlet: package com.west.webcourse.servlet; import java.i ...
- java 数据类型:Stream流 对象转换为集合collect(Collectors.toList()) ;常用方法count,limit,skip,concat,max,min
集合对象.stream() 获取流对象,对元素批处理(不改变原集合) 集合元素循环除了用for循环取出,还有更优雅的方式.forEach 示例List集合获取Stream对象进行元素批处理 impor ...
- 集合学习之"将集合对象List<Product>转换为Map"
将集合对象List<Product>转换为Map key = Product对象的sku value =Product对象 1 List<Product> products = ...
- JavaScript操作JSON的方法总结,JSON字符串转换为JSON对象
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,采用完全独立于语言的文本格式,是理想的数据交换格式.同时,JSON是 JavaScript 原生格式,这意 ...
随机推荐
- 让你彻底理解volatile,面试不再愁
本人免费整理了Java高级资料,涵盖了Java.Redis.MongoDB.MySQL.Zookeeper.Spring Cloud.Dubbo高并发分布式等教程,一共30G,需要自己领取.传送门:h ...
- PlayJava Day004
今日所学: /* 2019.08.19开始学习,此为补档. */ JDK 1.6:byte , int , short , char , enum JDK 1.7:byte , int , short ...
- DS12C887实时时钟
实物图 引脚定义 GND. VCC:直流电源,其中VCC接+5V输入,GND接地,当VCC输入为+5V时,用户可以访问DS12C887内RAM中的数据,并可对其进行读.写操作:当VCC的输入小于+4. ...
- 数据库 OR 运维 ____bayaim
最近一直在思考,想想未来的道路和自己努力的方向.马云曾说过现在的年轻人缺少“慢下来”,只有人慢下来才能更好思考,想好方法和目标才更靠近才成功.如果,一直不停的努力,在错误的道路越走越远,势必会浪费时间 ...
- Linux—各种重要配置文件详解
一./etc/profile文件详解(环境变量) 添加环境变量 .编辑profile文件 [root@localhost ~]# vi /etc/profile .在profile文件中添加如下内容 ...
- win10让屏幕壁纸动态变化某文件夹下的图片
首先,请大家在Win10系统中,点击桌面上的“开始菜单”,在开始菜单中,选择“设置”选项,进入Win10系统设置页面. 进入Win10系统设置页面以后,点击页面中的“个性化”选项,进入系统个性化页 ...
- SpringDataJpa-多表操作
多表之间的关系和操作多表的操作步骤 表关系 一对多 一对多 >> 一:主表 多:从表 多对多 >> 中间表中最少应该由两个字段组成,这两个字段作为 ...
- 9.Java基础_for/while/do-while循环
/* for循环(同C++) 初始化变量的作用域为循环体 出了循环体,初始化的局部变量消失 for(初始化;条件判断;条件控制){ 循环体; } while循环 while(条件判断){ 循环体; } ...
- pdfium ppm demo
#include "fpdfview.h" #include <iostream> #include <string> #include <strin ...
- 报错Error resolving template template might not exist or might not be accessible解决方案
"C:\Program Files\Java\jdk1.8.0_144\bin\java" "-javaagent:D:\IntelliJ IDEA Community ...