之前做过的项目中有个需要读取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到集合对象的更多相关文章

  1. .NET Core 使用NPOI读取Excel返回泛型List集合

    我是一名 ASP.NET 程序员,专注于 B/S 项目开发.累计文章阅读量超过一千万,我的博客主页地址:https://www.itsvse.com/blog_xzz.html 网上有很多关于npoi ...

  2. NPOI读取Excel表格类

    public class NPOIHelper    {        private HSSFWorkbook workbook;        public static IWorkbook Lo ...

  3. NPOI读取Excel遇到的坑

    NPOI是POI的.NET版本.POI是用Java写成的库,能帮助用户在没有安装Office环境下读取Office2003-2007文件.NPOI在.NET环境下使用,能读写Excel/Word文件. ...

  4. NET Excel转换为集合对象

    1.仅适用于规则Excel:表头和数据一一对应 2.涉及到Excel转换为集合对象的部分代码,完整npoi帮助类点击查看 /// <summary> /// 默认把excel第一个shee ...

  5. 使用NPOI读取Excel表格内容并进行修改

    前言 网上使用NPOI读取Excel文件的例子现在也不少,本文就是参考网上大神们的例子进行修改以适应自己需求的. 参考博文 http://www.cnblogs.com/restran/p/38894 ...

  6. NPOI读取Excel帮助类,支持xls与xlsx,实现公式解析,空行的处理

    NPOI读取Excel(2003或者2010)返回DataTable.支持公式解析,空行处理. /// <summary>读取excel /// 默认第一行为表头 /// </sum ...

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

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

  8. 使用NPOI读取Excel出错

    使用NPOI读取Excel出错,错误信息:java.io.IOException: Invalid header signature; read 4503608217567241, expected ...

  9. asp.net 使用NPOI读取excel文件

    asp.net 使用NPOI读取excel文件内容 NPOI下载地址:NPOI public class ExcelHelper { /// <summary> /// 读取Excel文件 ...

随机推荐

  1. programming-languages学习笔记--第3部分

    programming-languages学习笔记–第3部分 */--> pre.src {background-color: #292b2e; color: #b2b2b2;} pre.src ...

  2. [19/04/17-星期三] Java的动态性_反射(Reflection)机制

    一.前言 动态语言:程序运行时,可以改变程序结构或变量类型.典型的代表:Python,ruby,JavaScript 如JavaScript代码: function test(){ var s=&qu ...

  3. 【luogu P1606 [USACO07FEB]荷叶塘Lilypad Pond】 题解

    题目链接:https://www.luogu.org/problemnew/show/P1606 这个题..第一问很好想,但是第二问,如果要跑最短路计数的话,零边权的花怎么办? 不如这样想,如果这个点 ...

  4. 错误的另一个常见原因是默认的安全组规则。default security group默认情况下不允许ICMP(ping命令使用的协议)

    可以在openstack horizon界面中添加ICMP和ssh(TCP)规则,也可以通过命令行.命令行方式给默认安全组添加规则的方法如下: $ nova secgroup-add-rule def ...

  5. 算法学习记录-查找——平衡二叉树(AVL)

    排序二叉树对于我们寻找无序序列中的元素的效率有了大大的提高.查找的最差情况是树的高度.这里就有问题了,将无序数列转化为 二叉排序树的时候,树的结构是非常依赖无序序列的顺序,这样会出现极端的情况. [如 ...

  6. 爬虫 - xpath 匹配

    例题 import lxml.html test_data = """ <div> <ul> <li class="item-0& ...

  7. mysql 5.7 或以上版本 group by 问题记录

    mysql 5.7或以上的新版本sql_mode 默认开启开 ONLY_FULL_GROUP_BY,如果 select 中出现的字段,没有使用聚合函数,或不存在group by中就会提示,this i ...

  8. IIS配置导入导出

    使用管理员身份运行cmd 应用程序池: # 导出所有应用程序池 %windir%\system32\inetsrv\appcmd list apppool /config /xml > c:\a ...

  9. 局域网内python socket实现windows与linux间简单的消息传送

    有个需求,就是在windows上看见一篇介绍linux相关的文章,想在局域网内的另外一台linux电脑上尝试一下, 于是就需要把该网页链接发送给linux,不想一点一点敲链接,又苦于没有找到其它好的方 ...

  10. redis学习笔记(三)

    Spring data redis: 要求: Redis 版本 > 2.6 与 Lettuce 或 Jedis 集成,两种java开源Redis库. Spring redis主要做的两件事: 连 ...