NPOI+反射+自定义特性实现上传excel转List及验证
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及验证的更多相关文章
- 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的路由方案,与原来的方案在使用上差别不 ...
- 使用ocupload和POI一键上传Excel并解析导入数据库
使用的工具如下: JQuery ocupload jquery.ocupload-1.1.2.js Apache POI poi-3.9.jar 如果是Maven项目添加依赖如下: <depe ...
- java上传excel文件及解析
java上传excel文件及解析 CreateTime--2018年3月5日16:25:14 Author:Marydon 一.准备工作 1.1 文件上传插件:swfupload: 1.2 文件上 ...
- Django上传excel表格并将数据写入数据库
前言: 最近公司领导要统计技术部门在各个业务条线花费的工时百分比,而 jira 当前的 Tempo 插件只能统计个人工时.于是就写了个报表工具,将 jira 中导出的个人工时excel表格 导入数据库 ...
- 【vue】---- ElementUI 实现上传Excel
1.功能描述:vue 项目使用 el-upload 实现上传 Excel. 2.功能效果:在el-upload基础上做了样式整改. 3.功能实现: // el-upload 上传组件 <temp ...
- 微信公众平台上如何上传excel表格?
微信公众平台上如何上传excel表格? 我们都知道创建一个微信公众号,在公众号中发布一些文章是非常简单的,但公众号添加附件下载的功能却被限制,如今可以使用小程序“微附件”进行在公众号中添加附件. ...
- java的poi技术下载Excel模板上传Excel读取Excel中内容(SSM框架)
使用到的jar包 JSP: client.jsp <%@ page language="java" contentType="text/html; charset= ...
- SMW0上传EXCEL模板时报错无分配给对象***的MIME类型
在使用SMW0上传照片.声音文件.EXCEL模板等文件时,遇到报错提示,如下图所示: 解决办法:需要先维护 .XLS 文件的MIME TYPE,SMW0 打开如下图所示 选择上图红色框中“WebRFC ...
- Uploadify上传Excel到数据库
前两章简单的介绍了Uploadify上传插件的基本使用和相关的属性说明.这一章结合Uploadify+ssh框架+jquery实现Excel上传并保存到数据库. 以前写的这篇文章 Jq ...
随机推荐
- 用命令行执行ROBOT FRAMEWORK用例
转自:http://www.51testing.com/html/86/n-1430786.html 除了在ride中执行用例,我们也可以通过命令行的形式执行用例. 1.执行一整个项目 pybot+项 ...
- 批量执行命令:fabric
Fabric 可以通过 SSH 在多台客户端主机上批量执行任务,是基于 paramiko 封装开发的,paramiko 更底层一些,安装方法如下: [root@localhost ~]$ yum in ...
- 使用reactjs遇到Warning: setState(...): Can only update a mounted or mounting component.
前端数据大部分来源于后端,需要向后端发起异步请求,而在使用reactjs的时候,如果这个组件最初加载的时候就发起这个异步请求,然后在返回结果中进行setState({}),这时候有可能会遇到这个警告: ...
- KVO的用法、底层实现原理
KVO的用法 KVO也就是key-value-observing(即键值观察),利用一个key来找到某个属性并监听其值得改变.用法如下: 添加观察者 在观察者中实现监听方法,observeValueF ...
- .net 防盗链
Global.asax 文件中 protected void Application_BeginRequest(object sender, EventArgs e) { //判断当前请求是否是访问 ...
- Vscode 修改为中文语言
1 官网下载最新版的vscode : https://code.visualstudio.com/Download 2 安装之后, 按键 F1 搜索框 输入 language 选择 config ...
- web移动端一些常用知识
1.去掉 a,input 在移动端浏览器中的默认样式(半透明灰色遮罩阴影) a,button,input,optgroup,select,textarea { -webkit-tap-highligh ...
- java GC工作机制
转自:http://www.cnblogs.com/hzdtf/articles/5419987.html GC:垃圾回收站,是将java的无用的堆对象进行清理,释放内存,以免发生内存泄露.在介绍ja ...
- java设计模式----迭代子模式
顺序访问聚集中的对象,主要用于集合中.一是需要遍历的对象,即聚集对象,二是迭代器对象,用于对聚集对象进行遍历访问. 迭代子模式为遍历集合提供了统一的接口方法.从而使得客户端不需要知道聚集的内部结构就能 ...
- centos samba搭建
1.需求: 建立两个用户(zx,zxadmin),zxadmin能访问所有目录,zx只能访问指定目录. 2.安装smb [root@vi /]# yum install samba -y 3.创建用户 ...