1.自定义特性

[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class PropertyDescriptionAttribute : Attribute
{
private bool _allownullorempty = true;
public PropertyDescriptionAttribute() { }
/// <summary>
/// 是否允许为null或空值
/// </summary>
public bool AllowNullOrEmpty
{
get
{
return this._allownullorempty;
}
set
{
this._allownullorempty = value;
}
}
}

2.定义类(假设是用户信息)

public class UploadUserModel
{
[PropertyDescription(AllowNullOrEmpty = false)]
public string Name { get; set; }
[PropertyDescription(AllowNullOrEmpty = false)]
public string Phone { get; set; }
}

自定义特定来标识这两个信息不能为空

3.实现

/// <summary>
/// PROPERTY_NAME数组:值与excel列一一对应
/// </summary>
private readonly string[] PROPERTY_NAME = { "Name", "Phone" }; private List<UploadUserModel> ExcelToList(HttpPostedFile excelFile)
{
IWorkbook workbook = null;
ISheet sheet = null;
int colCount = ;
List<UploadUserModel> users = new List<UploadUserModel>();
if (excelFile.FileName.IndexOf(".xlsx") > )
{
workbook = new XSSFWorkbook(excelFile.InputStream);
}
else if (excelFile.FileName.IndexOf(".xls") > )
{
workbook = new HSSFWorkbook(excelFile.InputStream);
}
if (workbook != null)
{
sheet = workbook.GetSheetAt();
if (sheet != null && sheet.LastRowNum > )
{
colCount = sheet.GetRow().LastCellNum;//获取列数
//从第二行开始解析
for (int rowIndex = ; rowIndex <= sheet.LastRowNum; rowIndex++)
{
var curRow = sheet.GetRow(rowIndex);//获取当前行
UploadUserModel user = new UploadUserModel();
Type cType = user.GetType();
//解析列
for (int colIndex = ; colIndex < colCount; colIndex++)
{
var curCell = curRow.GetCell(colIndex);
if (curCell != null)
{
curCell.SetCellType(CellType.String);//把单元格设置成String类型,统一取值方式
}
//定义PROPERTY_NAME避免if判断
PropertyInfo propertyInfo = cType.GetProperty(PROPERTY_NAME[colIndex]);
//获取自定义特性
object[] customAttrs = propertyInfo.GetCustomAttributes(typeof(PropertyDescriptionAttribute), true);
if (customAttrs.Length > )
{
PropertyDescriptionAttribute attr = customAttrs[] as PropertyDescriptionAttribute;
if (!attr.AllowNullOrEmpty)//属性值不能为空
{
if (curCell == null)
{
throw new Exception("第" + (rowIndex + ).ToString() + "行有未填项,请填写后重新上传。");
}
else if (string.IsNullOrEmpty(curCell.StringCellValue))
{
throw new Exception("第" + (rowIndex + ).ToString() + "行有未填项,请填写后重新上传。");
}
}
object cellValue = null;
if (curCell == null)
{
cellValue = "";
}
else
{
cellValue = curCell.StringCellValue;
}
if (!propertyInfo.PropertyType.IsGenericType)
{
//非泛型
propertyInfo.SetValue(user, curCell == null ? null : Convert.ChangeType(cellValue, propertyInfo.PropertyType), null);
}
else
{
//泛型Nullable<>
Type genericTypeDefinition = propertyInfo.PropertyType.GetGenericTypeDefinition();
if (genericTypeDefinition == typeof(Nullable<>))
{
propertyInfo.SetValue(user, curCell == null ? null : Convert.ChangeType(cellValue, Nullable.GetUnderlyingType(propertyInfo.PropertyType)), null);
}
}
}
}
users.Add(user);
}
}
}
else
{
throw new Exception("Excel解析异常");
}
foreach (var item in users)
{
if (!checkPhoneGS(item.Phone))
{
throw new Exception("手机号格式不正确:"+ item.Phone);
}
}
return users;
}

不要看着麻烦,核心代码很简单。用反射和定义PROPERTY_NAME数组是为了代码重用。最后那段泛型、非泛型判断可以删除,估计一般用不到

NPOI+反射+自定义特性实现上传excel转List及验证的更多相关文章

  1. ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案 try.dot.net 的正确使用姿势 .Net NPOI 根据excel模板导出excel、直接生成excel .Net NPOI 上传excel文件、提交后台获取excel里的数据

    ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案   ASP.NET Core 从2.2版本开始,采用了一个新的名为Endpoint的路由方案,与原来的方案在使用上差别不 ...

  2. 使用ocupload和POI一键上传Excel并解析导入数据库

    使用的工具如下:  JQuery ocupload jquery.ocupload-1.1.2.js Apache POI poi-3.9.jar 如果是Maven项目添加依赖如下: <depe ...

  3. java上传excel文件及解析

      java上传excel文件及解析 CreateTime--2018年3月5日16:25:14 Author:Marydon 一.准备工作 1.1 文件上传插件:swfupload: 1.2 文件上 ...

  4. Django上传excel表格并将数据写入数据库

    前言: 最近公司领导要统计技术部门在各个业务条线花费的工时百分比,而 jira 当前的 Tempo 插件只能统计个人工时.于是就写了个报表工具,将 jira 中导出的个人工时excel表格 导入数据库 ...

  5. 【vue】---- ElementUI 实现上传Excel

    1.功能描述:vue 项目使用 el-upload 实现上传 Excel. 2.功能效果:在el-upload基础上做了样式整改. 3.功能实现: // el-upload 上传组件 <temp ...

  6. 微信公众平台上如何上传excel表格?

    微信公众平台上如何上传excel表格?   我们都知道创建一个微信公众号,在公众号中发布一些文章是非常简单的,但公众号添加附件下载的功能却被限制,如今可以使用小程序“微附件”进行在公众号中添加附件. ...

  7. java的poi技术下载Excel模板上传Excel读取Excel中内容(SSM框架)

    使用到的jar包 JSP: client.jsp <%@ page language="java" contentType="text/html; charset= ...

  8. SMW0上传EXCEL模板时报错无分配给对象***的MIME类型

    在使用SMW0上传照片.声音文件.EXCEL模板等文件时,遇到报错提示,如下图所示: 解决办法:需要先维护 .XLS 文件的MIME TYPE,SMW0 打开如下图所示 选择上图红色框中“WebRFC ...

  9. Uploadify上传Excel到数据库

    前两章简单的介绍了Uploadify上传插件的基本使用和相关的属性说明.这一章结合Uploadify+ssh框架+jquery实现Excel上传并保存到数据库.         以前写的这篇文章 Jq ...

随机推荐

  1. ZooKeeper(六)-- CAP和BASE理论、ZAB协议

    一.CAP理论和BASE理论 1.CAP理论 CAP理论,指的是在一个分布式系统中,不可能同时满足Consistency(一致性). Availability(可用性).Partition toler ...

  2. __declspec的用法

    __declspec用于指定所给定类型的实例与Microsoft相关的存储方式.其它的有关存储方式的修饰符如static与extern等是C和C++语言的ANSI规范,而__declspec是一种扩展 ...

  3. ajax的历史

    ajax (AJAX开发) 编辑 AJAX即“Asynchronous Javascript And XML”(异步JavaScript和XML),是指一种创建交互式网页应用的网页开发技术. AJAX ...

  4. java高级---->Thread之Exchanger的使用

    Exchanger可以在两个线程之间交换数据,只能是2个线程,他不支持更多的线程之间互换数据.今天我们就通过实例来学习一下Exchanger的用法. Exchanger的简单实例 Exchanger是 ...

  5. LeetCode——First Bad Version

    Description: You are a product manager and currently leading a team to develop a new product. Unfort ...

  6. Elasticsearch 常用基本查询

    安装启动很简单,参考官网步骤:https://www.elastic.co/downloads/elasticsearch 为了介绍Elasticsearch中的不同查询类型,我们将对带有下列字段的文 ...

  7. 徐州网络赛A-Hard To Prepare【dp】【位运算】【快速幂】

    After Incident, a feast is usually held in Hakurei Shrine. This time Reimu asked Kokoro to deliver a ...

  8. 实现VMware下CentOS和Windows之间的复制粘贴

    实现VMware下CentOS和Windows之间的复制粘贴1.第一步,打开虚拟机2.点击菜单栏中的虚拟机->安装VMware Tools3.桌面中找到VMwareTools-10.0.10-4 ...

  9. Oracle开发 之 主-外键约束FK及约束的修改

    试验环境: 1)数据库版本:oracle 11.2.0.4 2)建表脚本:以scott的dept及emp表为基础. 父表:dept -- Create table create table DEPT ...

  10. CentOS 6.7 配置LVM (逻辑卷管理)

    LVM 简介 LVM是逻辑盘卷组管理 (Logical Volume Manager) 的简称. LVM是建立在硬盘和分区之上的一个逻辑层,来提高磁盘分区管理的灵活性,在一定程度上解决普通磁盘分区带来 ...