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. 工作流JBPM_day01:4-管理流程定义

    工作流JBPM_day01:4-管理流程定义 管理流程(流程定义) 部署(添加) 查询 删除 查看流程图(xxx.png) -- 修改 --> 没有真正的修改,而是使用“再次部署+使用最新版本启 ...

  2. ArcGIS 要素合并

    1.选择工具 2.选择输入要素.输出要素.按照什么字段进行合并 3.查看融合结果 4.GP工具-创建GP模型 拖入“融合”工具,设置融合的参数,如下图: 右击左边椭圆,勾选 模型参数 右击右边椭圆,勾 ...

  3. weblogic11g重置控制密码

    Reset the AdminServer Password in WebLogic 11g and 12c If you forget the AdminServer password for yo ...

  4. Delphi的保存文件对话框-TsaveDialog

    TsaveDialog继承于TOpenDialog,只介绍以下几个内容: 1.TsaveDialog如何设定为保存的默认路径是当前程序所在的文件夹: 默认目录是当前程序所在目录应设置属性Initial ...

  5. LeetCode——Intersection of Two Linked Lists

    Description: Write a program to find the node at which the intersection of two singly linked lists b ...

  6. Android N 7 【 classes.dex】反编译失败:com.googlecode.d2j.DexException: not support version.

    Microsoft Windows [版本 6.1.7601]版权所有 (c) 2009 Microsoft Corporation.保留所有权利. D:\Android反编译工具[全]\2016\d ...

  7. html-withimg-loder

    由于 webpack 对 html 的处理不太好,打包 HTML 文件中的图片资源是相对来说最麻烦的.这里需要引用一个插件—— html-withimg-loder // 打包 HTML 文件中的图片 ...

  8. Android通知栏的高度获取

    public static int getStatusBarHeight(Context context){ Class<?> c = null; Object obj = null; F ...

  9. Hive格式化输出数据库和表详细信息

    hive> desc database extended wx_test; OK wx_test hdfs://ns1/user/hive/warehouse/wx_test.db hadoop ...

  10. Oracle之归档模式与非归档模式

    归档模式和非归档模式 在DBA部署数据库之初,必须要做出的最重要决定之一就是选择归档模式(ARCHIVELOG)或者非 归档模式(NOARCHIVELOG )下运行数据库.我们知道,Oracle 数据 ...