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. js 获取图片url的Blob值并预览

    1)使用 XMLHttpRequest 对象获取图片url的Blob值 //获取图片的Blob值 function getImageBlob(url, cb) { var xhr = new XMLH ...

  2. Android中的渐变

    LinearGradient的用法 LinearGradient linearGradient; linearGradient = new LinearGradient(0, 0, 0, getHei ...

  3. php学习十二:其他魔术方法

    __clone():克隆的时候会调用__clone方法: __cal:当类里面没有方法的时候会调用__call方法: __toString:当echo的时候会调用__toString方法: __aut ...

  4. OracleServiceORCL这个服务竟然不见了

    OracleServiceORCL这个服务竟然不见了,后数据库连接不成功,晕死,以前使用数据库还能看到,现在竟然不见了?Why?我猜测原因有二: ①:电脑已经装了Oracle数据库后又装了MySql数 ...

  5. 在lampp的proftpd下新增FTP用户的方法与配置

    用LAMPP的安装方法可以开一个默认的lampp用户,不过多用户怎样管理.目录怎样设置?这里简明说一下. 要求:使用Lampp的proftpd,开通多个FTP用户,并各分配一个目录,而且需要限制用户在 ...

  6. String.Join重载String.Join 方法 (String, String[], Int32, Int32)

    https://msdn.microsoft.com/zh-cn/library/tk0xe5h0 String.Join 方法 (String, String[], Int32, Int32) 官方 ...

  7. Servlet 工程 web.xml 中的 servlet 和 servlet-mapping 标签 《转载》

    摘录某个工程的 web.xml 文件片段: 访问顺序为1—>2—>3—>4,其中2和3的值必须相同. url-pattern 标签中的值是要在浏览器地址栏中输入的 url,可以自己命 ...

  8. 【原创】asp.net内部原理(三) 第三个版本 (最详细的版本)

    前言: 今天继续吧这个系列补齐,这几天公司的项目比较忙,回到家已经非常的累了,所以也没顾得上天天来这里分享一些东西和大家一起探讨,但是今天晚上我还是坚持打开电脑,分享一些asp.net生命周期的知识, ...

  9. Eclipse 真机调试检测不到手机解决方案

    想用Eclipse真机调试,但是死活检测不到手机. 手机已经打开了usb调试模式. 开始用的华为Mate9,后面试了下小米,都不行. 在网上搜了一堆,什么安全驱动.adb占用.删除360手机助手.修改 ...

  10. Thrift入门之mac下的安装流程

    新建一个maven项目,先下载maven依赖  http://thrift.apache.org/download <dependency> <groupId>org.apac ...