从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数据导入的更多相关文章

  1. Npoi将excel数据导入到sqlserver数据库

    /// <summary> /// 将excel导入到datatable /// </summary> /// <param name="filePath&qu ...

  2. 基于ElementUI封装Excel数据导入组件

    由于前端项目使用的是Vue-cli3.0 + TypeScript的架构,所以该组件也是基于ts语法封装的,组件的完整代码如下: <template> <div id="m ...

  3. 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility (续3篇-导出时动态生成多Sheet EXCEL)

    ExcelUtility 类库经过我(梦在旅途)近期不断的优化与新增功能,现已基本趋向稳定,功能上也基本可以满足绝大部份的EXCEL导出需求,该类库已在我们公司大型ERP系统全面使用,效果不错,今天应 ...

  4. 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility (续2篇-模板导出综合示例)

    自ExcelUtility类推出以来,经过项目中的实际使用与不断完善,现在又做了许多的优化并增加了许多的功能,本篇不再讲述原理,直接贴出示例代码以及相关的模板.结果图,以便大家快速掌握,另外这些示例说 ...

  5. 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility (续篇)

    上周六我发表的文章<分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility>受到了大家的热烈支持与推荐,再此表示感谢,该ExcelUtility ...

  6. 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility

    1. ExcelUtility功能:  1.将数据导出到EXCEL(支持XLS,XLSX,支持多种类型模板,支持列宽自适应)  类名:ExcelUtility. Export  2.将EXCEL ...

  7. 效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中【附源代码下载】) 转

    效率最高的Excel数据导入---(c#调用SSIS Package将数据库数据导入到Excel文件中[附源代码下载])    本文目录: (一)背景 (二)数据库数据导入到Excel的方法比较   ...

  8. 使用NPOI读取Excel数据到DataTable

    如今XML文件的存储格式大行其道,可是也不是适用于全部情况,非常多单位的数据交换还是使用Excel的形式.这就使得我们须要读取Excel内的数据.载入到程序中进行处理.可是如何有效率的读取,如何使程序 ...

  9. 批量Excel数据导入Oracle数据库

    由于一直基于Oracle数据库上做开发,因此常常会需要把大量的Excel数据导入到Oracle数据库中,其实如果从事SqlServer数据库的开发,那么思路也是一样的,本文主要介绍如何导入Excel数 ...

随机推荐

  1. 百度MIP页规范详解 —— canonical标签

    百度MIP的规范要求必须添加强制性标签canonical,不然MIP校验工具会报错: 强制性标签<link rel="/^(canonical)$/"> 缺失或错误 这 ...

  2. 【深入浅出jQuery】源码浅析--整体架构

    最近一直在研读 jQuery 源码,初看源码一头雾水毫无头绪,真正静下心来细看写的真是精妙,让你感叹代码之美. 其结构明晰,高内聚.低耦合,兼具优秀的性能与便利的扩展性,在浏览器的兼容性(功能缺陷.渐 ...

  3. Mysql事务探索及其在Django中的实践(二)

    继上一篇<Mysql事务探索及其在Django中的实践(一)>交代完问题的背景和Mysql事务基础后,这一篇主要想介绍一下事务在Django中的使用以及实际应用给我们带来的效率提升. 首先 ...

  4. 8、Struts2 运行流程分析

    1.流程分析: 请求发送给 StrutsPrepareAndExecuteFilter StrutsPrepareAndExecuteFilter 询问 ActionMapper: 该请求是否是一个 ...

  5. .net 分布式架构之配置中心

    开源QQ群: .net 开源基础服务  238543768 开源地址: http://git.oschina.net/chejiangyi/Dyd.BaseService.ConfigManager ...

  6. Go结构体实现类似成员函数机制

    Go语言结构体成员能否是函数,从而实现类似类的成员函数的机制呢?答案是肯定的. package main import "fmt" type stru struct { testf ...

  7. 个人网站对xss跨站脚本攻击(重点是富文本编辑器情况)和sql注入攻击的防范

    昨天本博客受到了xss跨站脚本注入攻击,3分钟攻陷--其实攻击者进攻的手法很简单,没啥技术含量.只能感叹自己之前竟然完全没防范. 这是数据库里留下的一些记录.最后那人弄了一个无限循环弹出框的脚本,估计 ...

  8. CSS 3 学习——渐变

    通过CSS渐变创建的是一个没有固定比例和固定尺寸的<image>类型,也就是说是一张图片,这张图片的尺寸由所应用的元素的相关信息决定.凡是支持图片类型的CSS属性都可以设置渐变,而支持颜色 ...

  9. 对百度WebUploader开源上传控件的二次封装,精简前端代码(两句代码搞定上传)

    前言 首先声明一下,我这个是对WebUploader开源上传控件的二次封装,底层还是WebUploader实现的,只是为了更简洁的使用他而已. 下面先介绍一下WebUploader 简介: WebUp ...

  10. css样式之border-radius

    border-radius 属性设置边框的园角 可能的值:像素,百分比 扩展延伸 html代码 <div></div> css代码 div { height: 200px; w ...