备注:
Demo项目创建的控制器为.NET Core3.1框架

1、控制台应用程序代码

using System;
using System.IO;namespace Excel_Import
{class Program{static void Main(string[] args){Console.WriteLine("开始执行导入Excel程序");var filePath = @"D:\Test\TestExcel.xlsx";using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read)){byte[] bytes = new byte[fileStream.Length];fileStream.Read(bytes, 0, bytes.Length);fileStream.Close();// 把 byte[] 转换成 StreamStream stream = new MemoryStream(bytes);var list = ExcelConvert.ToEntityStreamList<TestExcel>(stream, "TestExcel.xlsx");Console.WriteLine("开始遍历TestExcel");foreach (var item in list){Console.WriteLine($"姓名:{item.Name};地址:{item.Address}");}Console.WriteLine("遍历TestExcel结束");Console.ReadLine();}}}/// <summary>/// 测试Excel模型/// </summary>public class TestExcel{/// <summary>/// 姓名/// </summary>[ExcelColumn("姓名")]public string Name { get; set; }/// <summary>/// 分组/// </summary>[ExcelColumn("地址")]public string Address { get; set; }}
}

2、帮助类代码

using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;namespace Excel_Import
{/// <summary>/// Excel帮助类/// </summary>public class ExcelConvert{public static List<T> ToEntityStreamList<T>(Stream stream, string fileName, bool firstRow2Name = true) where T : new(){return ToEntityList<T>(stream, fileName);}/// <summary>/// Excel转换为实体列表【普通】/// </summary>/// <typeparam name="T">实体类</typeparam>/// <param name="fileInfo">文件信息</param>/// <param name="firstRow2Name">第一行是否做为列名,默认为true</param>/// <returns></returns>private static List<T> ToEntityList<T>(Stream stream, string fileName, bool firstRow2Name = true)where T : new(){// 加载ExcelIWorkbook workbook;try{// 格式判断if (fileName.EndsWith(".xlsx")){workbook = new XSSFWorkbook(stream);}else{workbook = new HSSFWorkbook(stream);}// 返回实体集var entities = new List<T>();// 读取第一页ISheet sheet = workbook.GetSheetAt(0);// 遍历所有行IEnumerator rows = sheet.GetRowEnumerator();// 反射实体判断实体行var columns = new List<EntityColumn>();#region 反射实体判断实体行对应Excel文件列// 名称行var excelFirstRow = new List<string>();if (firstRow2Name && rows.MoveNext()){var row = (IRow)rows.Current;for (int i = 0; i <= row.LastCellNum; i++){ICell cell = row.GetCell(i);if (cell == null) excelFirstRow.Add("");else excelFirstRow.Add(cell.ToString());}}// 反射PropertyInfo[] propertys = typeof(T).GetProperties();int propertyIndex = 0;foreach (PropertyInfo property in propertys){object[] excelColumns = property.GetCustomAttributes(typeof(ExcelColumnAttribute), true);if (excelColumns.Length > 0){string like = (excelColumns[0] as ExcelColumnAttribute).DisplayNameLike;int excelIndex = (excelColumns[0] as ExcelColumnAttribute).ExcelIndex;if (!string.IsNullOrEmpty(like)){for (int index = 0; index < excelFirstRow.Count; index++){if (excelFirstRow[index].Contains(like)){columns.Add(new EntityColumn { ColumnName = property.Name, ExcelIndex = index });break;}}}else if (excelIndex > -1){columns.Add(new EntityColumn { ColumnName = property.Name, ExcelIndex = excelIndex });}else{columns.Add(new EntityColumn { ColumnName = property.Name, ExcelIndex = propertyIndex });}}propertyIndex++;}#endregion// 遍历数据行while (rows.MoveNext()){var row = (IRow)rows.Current;var entity = new T();PropertyInfo[] items = entity.GetType().GetProperties();foreach (PropertyInfo property in items){EntityColumn column = columns.FirstOrDefault(t => t.ColumnName == property.Name);if (column != null){ICell cell = row.GetCell(column.ExcelIndex);if (cell == null)//if (column.ExcelIndex - row.FirstCellNum >= row.Cells.Count || column.ExcelIndex - row.FirstCellNum < 0){continue;}Object val = cell.ToString();#region 数据类型转换if (property.PropertyType == typeof(DateTime)){if (cell.CellType == CellType.Numeric){val = cell.DateCellValue;}else{DateTime d;DateTime.TryParse(val.ToString(), out d);val = d;}}else if (property.PropertyType == typeof(string)){val = val.ToString().Trim();}if (property.PropertyType == typeof(Int32)){if (cell.CellType == CellType.Numeric){val = (int)Math.Round(cell.NumericCellValue);}Int32 d;Int32.TryParse(val.ToString(), out d);val = d;}else if (property.PropertyType == typeof(UInt32)){if (cell.CellType == CellType.Numeric){val = Math.Round(cell.NumericCellValue);}UInt32 d;UInt32.TryParse(val.ToString(), out d);val = d;}else if (property.PropertyType == typeof(Int16)){if (cell.CellType == CellType.Numeric){val = Math.Round(cell.NumericCellValue);}Int16 d;Int16.TryParse(val.ToString(), out d);val = d;}else if (property.PropertyType == typeof(UInt16)){if (cell.CellType == CellType.Numeric){val = Math.Round(cell.NumericCellValue);}UInt16 d;UInt16.TryParse(val.ToString(), out d);val = d;}else if (property.PropertyType == typeof(float)){if (cell.CellType == CellType.Numeric){val = cell.NumericCellValue;}float d;float.TryParse(val.ToString(), out d);val = d;}else if (property.PropertyType == typeof(decimal)){if (cell.CellType == CellType.Numeric){val = cell.NumericCellValue;}decimal d;decimal.TryParse(val.ToString(), out d);val = d;}else if (property.PropertyType == typeof(double)){if (cell.CellType == CellType.Numeric){val = cell.NumericCellValue;}else{double d;double.TryParse(val.ToString(), out d);val = d;}}else if (property.PropertyType == typeof(byte)){if (cell.CellType == CellType.Numeric){val = (byte)Convert.ToInt32(cell.NumericCellValue);}else{double d;double.TryParse(val.ToString(), out d);val = (byte)d;}}#endregionproperty.SetValue(entity, val, null);}}entities.Add(entity);}// 返回结果return entities;}catch (Exception ex){}return null;}private class EntityColumn{public string ColumnName { get; set; }public int ExcelIndex { get; set; }}}/// <summary>/// Excel列属性【添加标签对象】/// </summary>public class ExcelColumnAttribute : Attribute{public ExcelColumnAttribute(){ExcelIndex = -1;}public ExcelColumnAttribute(int excelIndex){ExcelIndex = excelIndex;}public ExcelColumnAttribute(string displayNameLike){DisplayNameLike = displayNameLike;}public int ExcelIndex { get; set; }public string DisplayNameLike { get; set; }}}

结果:

Excel说明:
首行必须和定义类(TestExcel)中的标签名一致

C#导入Excel数据(简单)相关推荐

  1. python绘制动态图表怎么存下来_用python如何实现导入excel数据后自动生成图表?python如何实现交互式动态图表?...

    这个需求涉及的环节太多了.导入excel文件,获取数据 -- 需要xlrd模块把数据导入python 2. 设定输出图表类型 -- 需要matplot模块.根据数据复杂度,可能需要ETL,那么需要pa ...

  2. python导入excel数据-如何把python中的数据导入excel

    python将数据导入excel的方法:1.在python官网下载xlrd第三方库:2.利用xlrd中的open_workbook函数读入excel文件,即可在python中导入excel数据. 一. ...

  3. arcgis导入excel数据_导入Excel数据到ArcGIS属性表的两种实用方法

    导入Excel数据到ArcGIS有两种方法,一种是用ArcMap的加载数据(黄色+号那个):另一种是用ArcCatalog直接转为shp文件,两种方法的原理是一样的. 第一种方法 1.Excel数据: ...

  4. mysql导入excel表_mysql怎么导入excel数据?

    mysql导入excel数据的步骤: 1.第一步我们得到了一个excel表,里面有很多需要我们导入的数据. 2.删除第1行"准考证号""XXX"....只保留我 ...

  5. php导入excel先检查,php 如何在导入Excel数据时检查Mysql数据库内容是否存在,避免重复录入?:怎么样筛选excel表格重复的数据库...

    php 如何在导入Excel数据时检查Mysql数据库内容是否存在,避免重复录入? 如果不想每询一次以提前做一个统询 $sql=mysql_query("select distinct Co ...

  6. easyExcel 导入Excel数据

    easyExcel 导入Excel数据 最近公司项目需要导入几十万的Excel数据,我这里用的是现在最流行的easyExcel, 希望能帮助到你 首先导入jar包 <dependency> ...

  7. c 导入oracle数据库,c导入excel数据到数据库

    报表工具如何实现多次导入Excel 很多人在开发报表的时候会遇到将多张表样相同的excel导入到模板,然后提交至数据库中.但问题是很多情况,在线导入不支持一次性选择多个excel,一次只能选择一个ex ...

  8. 【二十四】springboot使用EasyExcel和线程池实现多线程导入Excel数据

      springboot篇章整体栏目:  [一]springboot整合swagger(超详细 [二]springboot整合swagger(自定义)(超详细) [三]springboot整合toke ...

  9. oracle 导入Excel数据

    oracle 导入excel数据 CreateTime--2018年1月30日14:58:51 Author:Marydon 通过plsql实现 1.准备工作 Excel中的字段名称,必须和表结构字段 ...

  10. php 导入表格数据,PHPExcel 导入Excel数据的方法

    这篇文章主要介绍了关于PHPExcel 导入Excel数据的方法,有着一定的参考价值,现在分享给大家,有需要的朋友可以参考一下 一:使用composer下载 phpoffice/phpexcel 或者 ...

最新文章

  1. 抢红包要当心!钱盾反诈平台专家揭秘3类假红包骗局
  2. 微信小程序通用开发框架小程序端包含若干基础组件
  3. python基础代码事例-python基础代码大全
  4. KindEditor编辑器在ASP.NET中的使用
  5. 零售业去“O”,不可逆之变
  6. nancy框架安装并使用
  7. 阿里巴巴JAVA开发手册及开发插件
  8. JavaScript图片库
  9. 汇编语言:实验10 根据材料编程—2.解决除法溢出的问题
  10. java,如何处理大批量数据插入
  11. mysql中count(*)、count(1)和count(字段)的区别
  12. 商城数据库模板mysql_ecshop 2.7.3仿京东jd商城源码 最新模板jd整站带数据支付插件...
  13. 【rzxt】笔者支招:电脑的散热大户显卡温度过高如何解决
  14. 笔记1-P2P后台管理系统
  15. 呼叫中心座席人员如何把控时间
  16. Ajax+JDBC+Json处理多个数据
  17. root 启动mysql_非root用户随开机而启动mysql服务
  18. 晟盾科技加入龙蜥社区,共建开源新生态
  19. 破解微信 DB, 导出 Mac 微信聊天记录
  20. 高等数学(第七版)同济大学 习题6-2 (前12题)个人解答

热门文章

  1. 用 Python 分析资产收益的典型化事实
  2. batch软件功能测试,Batch SMART 最强序列特征[结构域]预测软件
  3. iOS 12 - iOS 15,如何在iPhone上设置“早上好”功能
  4. 6-1 计算捐款总量 (10分)
  5. MATLAB 绘制时钟(同步当前时间)
  6. 【面试篇】ConcurrentHashMap1.7和1.8详解对比
  7. python保存图片的常用方法
  8. ei拼音的四个声调对应的字_幼儿园学前班拼音教案:复习 ei 以及四声调
  9. Vue中 引入使用 vue-json-views
  10. 使用Charles 抓取数据包