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文件 ...
随机推荐
- css注入获取网页中的数据
<style><?php echo htmlspecialchars($_GET['x']);?></style> <br><br>< ...
- [转载] MySQL数据库5.X版本基本手工注入总结
MySQL数据库5.X版本基本手工注入总结 根据我对MySQL的认识,注入时,基本可以通过爆.盲注.报错三种方式获得用户名和密码,在权限足够的情况下,还可以直接通过SQL语句插入并导出我们的一句话we ...
- 如何弹出WiFi提示列表。
如果你的程序中用到了WiFi,想在没有有效WiFi的时候出现如图所示的提示该怎么做? 其实很简单, 只需要在Info.plist中添加如下Key/Value UIRequiresPersistentW ...
- spring boot 输入参数统一校验
1 引入spring boot validate maven 依赖 <!-- 验证 --> <dependency> <groupId>org.hiberna ...
- version 1.5.2-04 of the jvm is not suitable for this product. version:1.6 or greater is required
这里仅仅说明一个可能造成该问题的解决办法,也是我遇到的原因. 这句话的意思是说,eclipse须要至少1.6版本号或以上的JVM ,而你仅仅有1.5.2版本号的JVM.想想就认为非常奇怪,我装的但是J ...
- (Les16 执行数据库恢复)-重做日志文件恢复
丢失重做日志文件 丢失了重做日志文件组中的某个成员,并且组中至少还有一个成员: -不会影响实例的正常操作. -预警日志中会收到一条信息, ...
- Mysql数据库-DAY2
查找 Select 字段(全部查找为*)from 表 增加 Insert into 字段(全部增加为表) values(需要增加的内容,用'','隔开') 删除 Delete from 表 where ...
- SQL分页过多时, 如何优化
问题: 我们经常会使用到分页操作,这里有个问题,在偏移量非常大的时候,它会导致MySQL扫描大量不需要的行然后再抛弃掉.如: , ; 上述这条SQL语句需要查询10020条记录然后只返回最后20条.前 ...
- CentOS6安装各种大数据软件 第五章:Kafka集群的配置
相关文章链接 CentOS6安装各种大数据软件 第一章:各个软件版本介绍 CentOS6安装各种大数据软件 第二章:Linux各个软件启动命令 CentOS6安装各种大数据软件 第三章:Linux基础 ...
- 如何做好一个优秀的web项目心得
最近利用空余的时间(坐公交车看教程视频),想了很多自己做的做果项目的优缺点,重新了解了前后端分离,前端工程化等概念学习,思考如何打造好一个优秀的web前端项目. 前端准备篇 前端代码规范:制定前端开发 ...