NPOI读取Excel到集合对象
之前做过的项目中有个需要读取Excel文件内容的需求,因此使用NPOI实现,写下以下代码,这个只是一个代码段,还有很多地方需要优化,希望能对大家有所帮助
public static IList<T> ReadListFromStream<T>(string fileName, Stream stream, bool ignoreFirstLine)
where T : new()
{
string extendsion = Path.GetExtension(fileName).TrimStart('.'); IWorkbook workBook = null;
switch (extendsion)
{
case "xls":
workBook = new HSSFWorkbook(stream);
break;
case "xlsx":
workBook = new XSSFWorkbook(stream);
break;
} if (workBook == null || workBook.Count <= 0) { throw new NPOIException("Excel表格工作簿为空"); } IList<T> list = new List<T>();
for (int i = 0; i < workBook.Count; i++)
{
ISheet sheet = workBook.GetSheetAt(i); if (sheet.PhysicalNumberOfRows > 0)
{
if (!ignoreFirstLine)
{
//检查列是否与ExcelAttribute定义的一致
ValidTableHeader<T>(sheet);
} for (int j = ignoreFirstLine ? 0 : 1; j < sheet.PhysicalNumberOfRows; j++)
{
var row = sheet.GetRow(j); T entity = new T(); var propertys = typeof(T).GetProperties(); foreach (var p in propertys)
{
var excel = Attribute.GetCustomAttribute(p, typeof(ExcelAttribute)) as ExcelAttribute; if (excel != null)
{
var cellValue = row.GetCell(excel.ColumnIndex); if (cellValue == null || string.IsNullOrEmpty(cellValue.ToString()))
throw new NPOIException(string.Format("第{0}行“{1}”不能为空", j + 1, excel.ColumnName)); string cellValueStr = cellValue.ToString();
if (p.PropertyType == typeof(int))
{
int temp;
if (!int.TryParse(cellValueStr, out temp))
throw new NPOIException(string.Format("第{0}行“{1}”应为{2}类型", j + 1, excel.ColumnName, "整数"));
p.SetValue(entity, temp, null);
}
else if (p.PropertyType == typeof(DateTime))
{
DateTime temp;
if (!DateTime.TryParse(cellValueStr, out temp))
throw new NPOIException(string.Format("第{0}行“{1}”应为{2}类型", j + 1, excel.ColumnName, "时间"));
p.SetValue(entity, temp, null);
}
else if (p.PropertyType == typeof(bool))
{
bool temp;
if (!bool.TryParse(cellValueStr, out temp))
throw new NPOIException(string.Format("第{0}行“{1}”应为{2}类型", j + 1, excel.ColumnName, "布尔"));
p.SetValue(entity, cellValueStr, null);
}
else if (p.PropertyType == typeof(string))
{
p.SetValue(entity, cellValueStr, null);
}
else
{
throw new NPOIException(string.Format("第{0}行“{1}”类型未知,请联系开发人员", j + 1, excel.ColumnName));
}
}
}
list.Add(entity);
}
}
}
return list;
} /// <summary>
/// 检查表头与定义是否匹配
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="firstRow"></param>
/// <returns></returns>
private static void ValidTableHeader<T>(ISheet sheet) where T : new()
{
var firstRow = sheet.GetRow(0); var propertys = typeof(T).GetProperties(); foreach (var p in propertys)
{
var excel = Attribute.GetCustomAttribute(p, typeof(ExcelAttribute)) as ExcelAttribute; if (excel != null)
{
if (!firstRow.GetCell(excel.ColumnIndex).StringCellValue.Trim().Equals(excel.ColumnName))
{
throw new NPOIException(string.Format("Excel表格第{0}列标题应为{1}", excel.ColumnIndex + 1, excel.ColumnName));
}
}
}
}
ExcelAttribute是自定义的一个特性类,主要在实体属性上标记,以确定该属性对应于Excel中的列名,列的索引
[AttributeUsage(AttributeTargets.Property)]
public class ExcelAttribute : Attribute
{
private string _columnName; public string ColumnName
{
get { return _columnName; }
set { _columnName = value; }
}
private int _columnIndex; public int ColumnIndex
{
get { return _columnIndex; }
set { _columnIndex = value; }
} public ExcelAttribute(string columnName)
{
this._columnName = columnName;
} public ExcelAttribute(string columnName, int columnIndex)
{
this._columnName = columnName;
this._columnIndex = columnIndex;
}
}
NPOI读取Excel到集合对象的更多相关文章
- .NET Core 使用NPOI读取Excel返回泛型List集合
我是一名 ASP.NET 程序员,专注于 B/S 项目开发.累计文章阅读量超过一千万,我的博客主页地址:https://www.itsvse.com/blog_xzz.html 网上有很多关于npoi ...
- NPOI读取Excel表格类
public class NPOIHelper { private HSSFWorkbook workbook; public static IWorkbook Lo ...
- NPOI读取Excel遇到的坑
NPOI是POI的.NET版本.POI是用Java写成的库,能帮助用户在没有安装Office环境下读取Office2003-2007文件.NPOI在.NET环境下使用,能读写Excel/Word文件. ...
- NET Excel转换为集合对象
1.仅适用于规则Excel:表头和数据一一对应 2.涉及到Excel转换为集合对象的部分代码,完整npoi帮助类点击查看 /// <summary> /// 默认把excel第一个shee ...
- 使用NPOI读取Excel表格内容并进行修改
前言 网上使用NPOI读取Excel文件的例子现在也不少,本文就是参考网上大神们的例子进行修改以适应自己需求的. 参考博文 http://www.cnblogs.com/restran/p/38894 ...
- NPOI读取Excel帮助类,支持xls与xlsx,实现公式解析,空行的处理
NPOI读取Excel(2003或者2010)返回DataTable.支持公式解析,空行处理. /// <summary>读取excel /// 默认第一行为表头 /// </sum ...
- 使用NPOI读取Excel数据到DataTable
如今XML文件的存储格式大行其道,可是也不是适用于全部情况,非常多单位的数据交换还是使用Excel的形式.这就使得我们须要读取Excel内的数据.载入到程序中进行处理.可是如何有效率的读取,如何使程序 ...
- 使用NPOI读取Excel出错
使用NPOI读取Excel出错,错误信息:java.io.IOException: Invalid header signature; read 4503608217567241, expected ...
- asp.net 使用NPOI读取excel文件
asp.net 使用NPOI读取excel文件内容 NPOI下载地址:NPOI public class ExcelHelper { /// <summary> /// 读取Excel文件 ...
随机推荐
- Zookeeper学习之路 (一)初识
本文引用自 http://www.cnblogs.com/sunddenly/p/4033574.html 引言 Hadoop 集群当中 N 多的配置信息如何做到全局一致并且单点修改迅速响应到整个集群 ...
- [Python web开发] Web框架开发基础 (一)
Python WEB框架 WSGI,WEB Server Gateway Interface,可以看做是一种底层协议,它规定了服务器程序和应用程序各自实现上面接口.Python的实现称为wsgiref ...
- java二维码工具类,中间带LOGO的,很强大
jar包下载maven 配置: Xml代码 收藏代码 <dependency> <groupId>com.google.zxing</groupId> <ar ...
- iOS之LLDB调试器
LLDB被定位为下一代的高性能调试器,默认内置于Xcode IDE内, 支持在PC.iOS设备以及模拟器上调试C.Objective-C和C++. 关于LLDB的官方介绍:LLDB 常用命令: 1. ...
- Unity-iPhone has Conflicting Provisioning Settings
Select the top level node called Unity-iPhone in the left tree view (the one with the blue item). Se ...
- leyer不写content参数直接传递给子页面数据
function btnAddClickownfund(){ //获取数据 var actual = $("#actual_capitals").html().trim(); // ...
- python使用ctypes模块下的windll.LoadLibrary报OSError: [WinError 193] % 不是有效的 Win32 应用程序
原因:python是64位的python,而windll.LoadLibrary只能由32位的python使用 参考: 64位Python调用32位DLL方法(一) 解决方法:使用32位的python ...
- 什么是cookie,作用是什么? 以及session的理解
cookie: 1.定义:什么是cookie? cookie就是存储在客户端的一小段文本 2.cookie是一门客户端的技术,因为cookie是存储在客户端浏览器中的 3.cookie的作用:是为了 ...
- decodeURI、decodeURIComponent 编码方法
——摘自<JavaScript高级程序设计> 编码: Global 对象的 encodeURI()和 encodeURIComponent()方法可以对 URI(Uniform Resou ...
- redis迁移复制数据,主从关系建立实践
装redis的机器出了点问题,需要转移数据然后初始化系统,然后我就研究了下redis的数据复制,发现了slaveof 192.168.0.1 6379这个命令,开始踩下这个坑 首先要新的服务器上进入r ...