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. Taro多端自定义导航栏Navbar+Tabbar实例

    运用Taro实现多端导航栏/tabbar实例 (H5 + 小程序 + React Native) 最近一直在捣鼓taro开发,虽说官网介绍支持编译到多端,但是网上大多数实例都是H5.小程序,很少有支持 ...

  2. SILK编码语音转WAV格式

    - SILK编码 SILK采样率可为8.12.16或24 kHz,比特率可为6至40 kbit/s.对应到报文层面的直观印象,即SILK编码的语音数据每帧长度是不等的. SILK编码已经开源,目前可下 ...

  3. 查看UNDO 表空间使用情况

    Select Sum(bytes / (1024 * 1024)), a.status    From dba_undo_extents a   Group By a.status Select fi ...

  4. mysql简单的sql操作语句

    一,常用.简单的SQL操作语句 1.数据库操作: 1)创建数据库: create database database_name: 创建并设置字符编码 create database database_ ...

  5. 4. static修饰符

    一.static修饰符概述 1. static修饰的成员表明它属于这个类本身,而不属于该类的单个实例 把static修饰的成员变量和方法称为类变量.类方法 2. 不使用static修饰的成员则属于该类 ...

  6. [转]5 种使用 Python 代码轻松实现数据可视化的方法

    数据可视化是数据科学家工作中的重要组成部分.在项目的早期阶段,你通常会进行探索性数据分析(Exploratory Data Analysis,EDA)以获取对数据的一些理解.创建可视化方法确实有助于使 ...

  7. XML配置报错

    警告: Exception encountered during context initialization - cancelling refresh attempt: org.springfram ...

  8. pugixml的简单使用

    一.简介 pugixml的官方主页为:http://pugixml.org/ pugixml是一个很棒的XML操作库, 它很轻量,只有三个文件(pugiconfig.hpp   pugixml.cpp ...

  9. IEEE754 浮点数

    IEEE754 浮点数 1.阅读IEEE754浮点数 A,阶码是用移码表示的,这里会有一个127的偏移量,它的127相当于0,小于127时为负,大于127时为正,比如:10000001表示指数为129 ...

  10. centos7.6离线安装mysql5.7(附下载链接)

    本来打算直接用原生yum源安装,但是跨国访问网络太慢,只好采用离线安装的方式,原理就是把所需的rpm下载下来再上传服务器安装. 1.rpm文件下载地址: 目录: http://repo.mysql.c ...