基于NPOI的Excel数据导入
从Excel导入数据最令人头疼的是数据格式的兼容性,特别是日期类型的兼容性。为了能够无脑导入日期,折腾了一天的NPOI。在经过测试确实可以导入任意格式的合法日期后,写下这篇小文,与大家共享。完整代码请移步:https://github.com/xuanbg/Utility
2016-11-13 04:06 修正一个bug。由try DateCellValue改为判断列数据类型,如类型为DateTiime返回DateCellValue,否则返回NumericCellValue或StringCellValue。
概述:
这个帮助类是一个泛型类,泛型参数对应的实体类还起到模板的作用。如果你的Excel文件使用与实体类不同的列标题的话,可以通过给属性加上Alias特性,将列标题和属性进行对应。例如:
Excel格式如图:

实体类:
using System;
using Insight.Utils.Common; namespace Insight.WS.Server.Common.Entity
{
public class Logistics
{
[Alias("订单号")]
public string OrderCode { get; set; } [Alias("物流公司")]
public string Service { get; set; } [Alias("物流单号")]
public string Number { get; set; } [Alias("发货时间")]
public DateTime DeliveryTime { get; set; }
}
}
返回的Json:
[
{
"OrderCode": "201611S1200324",
"Service": "顺丰",
"Number": "33012231F54351",
"DeliveryTime": "2016-11-10T11:02:44"
},
{
"OrderCode": "",
"Service": "顺丰",
"Number": "33012231F54352",
"DeliveryTime": "2016-11-12T09:02:44"
},
{
"OrderCode": "",
"Service": "EMS",
"Number": "33012231F54353",
"DeliveryTime": "2016-11-12T09:02:44"
}
]
1、类主体,负责根据传入的文件路径读取数据,并调用其他私有方法对数据进行处理。最后转换成List<T>并序列化成Json返回。
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using Insight.Utils.Entity;
using NPOI.SS.UserModel; namespace Insight.Utils.Common
{
public class NpoiHelper<T> where T : new()
{
private readonly Result _Result = new Result(); /// <summary>
/// 导入Excel文件
/// </summary>
/// <param name="path">文件路径</param>
/// <param name="index">Sheet索引</param>
/// <returns>Result</returns>
public Result Import(string path, int index = )
{
if (!File.Exists(path))
{
_Result.FileNotExists();
return _Result;
} IWorkbook book;
using (var file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
book = WorkbookFactory.Create(file);
} if (index >= book.NumberOfSheets)
{
_Result.SheetNotExists();
return _Result;
} var sheet = book.GetSheetAt(index);
var table = GetSheetData(sheet);
var list = Util.ConvertToList<T>(table);
_Result.Success(list);
return _Result;
}
}
}
2、GetSheetData方法,负责将Sheet中的数据读取到DataTable。这里通过实体类属性的特性值作为列名,属性类型作为列数据类型来初始化DataTable。当然,首行是例外,因为首行是列标题而非数据。
/// <summary>
/// 读取Sheet中的数据到DataTable
/// </summary>
/// <param name="sheet">当前数据表</param>
/// <returns>DataTable</returns>
private DataTable GetSheetData(ISheet sheet)
{
var table = InitTable(sheet);
if (table == null) return null; var rows = sheet.GetEnumerator();
while (rows.MoveNext())
{
var row = (IRow) rows.Current;
if (row.RowNum == ) continue; var dr = table.NewRow();
for (var i = ; i < table.Columns.Count; i++)
{
try
{
var type = table.Columns[i].DataType;
dr[i] = GetCellData(row.GetCell(i), type);
}
catch (Exception)
{
dr[i] = DBNull.Value;
} }
table.Rows.Add(dr);
} return table;
}
初始化DataTable的方法:
/// <summary>
/// 初始化DataTable
/// </summary>
/// <param name="sheet">当前数据表</param>
/// <returns>DataTable</returns>
private DataTable InitTable(ISheet sheet)
{
var title = sheet.GetRow();
if (title == null)
{
_Result.NoRowsRead();
return null;
} try
{
var dict = GetDictionary();
var table = new DataTable();
foreach (var cell in title.Cells)
{
var col_name = cell.StringCellValue;
var col_type = dict[col_name];
table.Columns.Add(cell.StringCellValue, col_type);
} return table;
}
catch
{
_Result.IncorrectExcelFormat();
return null;
}
}
生成模板字典的方法:
/// <summary>
/// 获取指定类型的属性名称/类型字典
/// </summary>
/// <returns>Dictionary</returns>
private Dictionary<string, Type> GetDictionary()
{
var dict = new Dictionary<string, Type>();
var propertys = typeof(T).GetProperties();
foreach (var p in propertys)
{
string name;
var attributes = p.GetCustomAttributes(typeof(AliasAttribute), false);
if (attributes.Length > )
{
var type = (AliasAttribute)attributes[];
name = type.Alias;
}
else
{
name = p.Name;
} dict.Add(name, p.PropertyType);
} return dict;
}
3、重点来了!
因为日期/时间在Excel中可能被表示为文本格式或日期格式(其实是Numeric类型),所以在CellType为String/Numeric的时候,如果列数据类型为DateTime,则取cell的DateCellValue,否则取cell的StringCellValue/NumericCellValue就好了。
这样,无论日期是文本或日期格式,都可以完美获取。
/// <summary>
/// 读Excel单元格的数据
/// </summary>
/// <param name="cell">Excel单元格</param>
/// <param name="type">列数据类型</param>
/// <returns>object 单元格数据</returns>
private object GetCellData(ICell cell, Type type)
{
switch (cell.CellType)
{
case CellType.Numeric:
if (type == typeof(DateTime)) return cell.DateCellValue; return cell.NumericCellValue; case CellType.String:
if (type == typeof(DateTime)) return cell.DateCellValue; return cell.StringCellValue; case CellType.Boolean:
return cell.BooleanCellValue; case CellType.Unknown:
case CellType.Formula:
case CellType.Blank:
case CellType.Error:
return null;
default:
return null;
}
}
4、DataTable转成List<T>的方法:
/// <summary>
/// 将DataTable转为List
/// </summary>
/// <param name="table">DataTable</param>
/// <returns>List</returns>
public static List<T> ConvertToList<T>(DataTable table) where T: new()
{
var list = new List<T>();
var propertys = typeof(T).GetProperties();
foreach (DataRow row in table.Rows)
{
var obj = new T();
foreach (var p in propertys)
{
string name;
var attributes = p.GetCustomAttributes(typeof(AliasAttribute), false);
if (attributes.Length > )
{
var type = (AliasAttribute) attributes[];
name = type.Alias;
}
else
{
name = p.Name;
} if (table.Columns.Contains(name))
{
if (!p.CanWrite) continue; var value = row[name];
if (value == DBNull.Value) value = null; p.SetValue(obj, value, null);
}
}
list.Add(obj);
}
return list;
}
自定义特性:
using System; namespace Insight.Utils.Common
{
[AttributeUsage(AttributeTargets.Property)]
public class AliasAttribute : Attribute
{
/// <summary>
/// 属性别名
/// </summary>
public string Alias { get; } /// <summary>
/// 构造方法
/// </summary>
/// <param name="alias">别名</param>
public AliasAttribute(string alias)
{
Alias = alias;
}
}
}
请大家对此多发表意见和建议,谢谢。
基于NPOI的Excel数据导入的更多相关文章
- Npoi将excel数据导入到sqlserver数据库
/// <summary> /// 将excel导入到datatable /// </summary> /// <param name="filePath&qu ...
- 基于ElementUI封装Excel数据导入组件
由于前端项目使用的是Vue-cli3.0 + TypeScript的架构,所以该组件也是基于ts语法封装的,组件的完整代码如下: <template> <div id="m ...
- 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility (续3篇-导出时动态生成多Sheet EXCEL)
ExcelUtility 类库经过我(梦在旅途)近期不断的优化与新增功能,现已基本趋向稳定,功能上也基本可以满足绝大部份的EXCEL导出需求,该类库已在我们公司大型ERP系统全面使用,效果不错,今天应 ...
- 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility (续2篇-模板导出综合示例)
自ExcelUtility类推出以来,经过项目中的实际使用与不断完善,现在又做了许多的优化并增加了许多的功能,本篇不再讲述原理,直接贴出示例代码以及相关的模板.结果图,以便大家快速掌握,另外这些示例说 ...
- 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility (续篇)
上周六我发表的文章<分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility>受到了大家的热烈支持与推荐,再此表示感谢,该ExcelUtility ...
- 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility
1. ExcelUtility功能: 1.将数据导出到EXCEL(支持XLS,XLSX,支持多种类型模板,支持列宽自适应) 类名:ExcelUtility. Export 2.将EXCEL ...
- 效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中【附源代码下载】) 转
效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中[附源代码下载]) 本文目录: (一)背景 (二)数据库数据导入到Excel的方法比较 ...
- 使用NPOI读取Excel数据到DataTable
如今XML文件的存储格式大行其道,可是也不是适用于全部情况,非常多单位的数据交换还是使用Excel的形式.这就使得我们须要读取Excel内的数据.载入到程序中进行处理.可是如何有效率的读取,如何使程序 ...
- 批量Excel数据导入Oracle数据库
由于一直基于Oracle数据库上做开发,因此常常会需要把大量的Excel数据导入到Oracle数据库中,其实如果从事SqlServer数据库的开发,那么思路也是一样的,本文主要介绍如何导入Excel数 ...
随机推荐
- Java多线程基础学习(二)
9. 线程安全/共享变量——同步 当多个线程用到同一个变量时,在修改值时存在同时修改的可能性,而此时该变量只能被赋值一次.这就会导致出现“线程安全”问题,这个被多个线程共用的变量称之为“共享变量”. ...
- SQL Server相关书籍
SQL Server相关书籍 (排名不分先后) Microsoft SQL Server 企业级平台管理实践 SQL Server 2008数据库技术内幕 SQL Server性能调优实战 SQL S ...
- Cassandra简介
在前面的一篇文章<图形数据库Neo4J简介>中,我们介绍了一种非常流行的图形数据库Neo4J的使用方法.而在本文中,我们将对另外一种类型的NoSQL数据库——Cassandra进行简单地介 ...
- Webpack 配置摘要
open-browser-webpack-plugin 自动打开浏览器 html-webpack-plugin 通过 JS 生成 HTML webpack.optimize.UglifyJsPlugi ...
- 记录一则Linux SSH的互信配置过程
需求:四台Linux主机,IP地址为192.168.10.10/11/12/13,配置登录用户的互信 1.各节点ssh-keygen生成RSA密钥和公钥 ssh-keygen -q -t rsa -N ...
- 微信网页开发之获取用户unionID的两种方法--基于微信的多点登录用户识别
假设网站A有以下功能需求:1,pc端微信扫码登录:2,微信浏览器中的静默登录功能需求,这两种需求就需要用到用户的unionID,这样才能在多个登录点(终端)识别用户.那么这两种需求下用户的unionI ...
- CSS知识总结(九)
CSS常用样式 10.自定义动画 1)关键帧(keyframes) 被称为关键帧,其类似于Flash中的关键帧. 在CSS3中其主要以“@keyframes”开头,后面紧跟着是动画名称加上一对花括号“ ...
- input type='file'上传控件假样式
采用bootstrap框架样式 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> &l ...
- MySQL常用命令
数据库登陆命令: mysql -uroot -p 2.提示输入密码: 3.登陆成功: 4.数据库修改相关命令: 修改数据库的编码格式: 语法格式为:ALTER {DATABASE|SCHEMA} [ ...
- spring mvc 数据校验
1.需要导入的jar包: slf4j-api-1.7.21.jar validation-api-1.0.0.GA.jar hibernate-validator-4.0.1.GA.jar 2.访问页 ...