之前做过的项目中有个需要读取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. 【vue】饿了么项目-header组件开发

    1.数据传递的理解 在App.vue中用到了header组件,首先注册组件 components: { 'v-header': header } 然后才能引用 <v-header :seller ...

  2. FRM一级备考感想

    作为金融小白,工作四年多,边边角角有了些许的最直观认识,决定深入了解下金融相关123. 曾经尝试CFA失败,转战FRM安慰下失败的灵魂. 2018.11.17 FRM Part I 考试结束,自7月初 ...

  3. Kali-linux使用SET实施攻击

    前面介绍了社会工程学工具包(SET)的简单使用.为了能帮助用户更容易的理解社会工程学的强大功能.本节将介绍使用社会工程学工具包实施各种攻击. 7.4.1 针对性钓鱼攻击向量 针对性钓鱼攻击向量通过构造 ...

  4. Vue系列——在vue项目中使用echarts

    该示例使用 vue-cli 脚手架搭建 安装echarts依赖 npm install echarts -S 或者使用国内的淘宝镜像安装 npm install -g cnpm --registry= ...

  5. sharepoint rest 脚本发送邮件

    function processSendEmails() { var from = 'asad@Example.com', to = 'someone@Example.com', body = 'He ...

  6. SpringBoot 动态打包

    配置pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="h ...

  7. 【mySQL】 - 主键

    什么是主键? 对于表中的每一行数据,都会有一个字段或一组字段,用于标识自己的唯一性,这样的一个或一组字段,就叫主键 如果没有这个主键,那么对于表中的每一行的管理,会陷入混乱,我要更新某一特定行的数值, ...

  8. 《Python高性能编程》——列表、元组、集合、字典特性及创建过程

    这里的内容仅仅是本人阅读<Python高性能编程>后总结的一些知识,用于自己更好的了解Python机制.本人现在并不从事计算密集型工作:人工智能.数据分析等.仅仅只是出于好奇而去阅读这本书 ...

  9. LR--用栈实现移进--归约分析(demo)

    1.考虑文法 \(E->E+E\) \(E->E*E\) \(E->id\) 2.最右推导 不难看出,这个文法是而二义的,所以有多个最右推导 3.移进归约 用一个栈存文法符号,用输入 ...

  10. mysql 常用的时间日期函数小结

    本文主要是总结一些常用的在实际运用中常用的一些mysql时间日期以及转换的函数 1.now()  :返回当前日期和时间 select now(); //2018-04-21 09:19:21 2.cu ...