Excel单元格校验

​ 使用Excel批量导入数据,为了避免一些脏数据,在读取Excel文件之后需要对Excel单元格进行校验;具体实现方式如下:

1、配置文件校验格式

{"1031": {"name": "1031","code": "person","column": [{ "name": "所属机构", "type": "GBString", "code": "ndkey" , "rules": [ { "message": "所属机构不允许为空", "name": "required" } ] },{ "name": "用户姓名", "type": "GBString", "code": "usrNam", "rules": [ { "message": "用户姓名不允许为空", "name": "required" } ] },{ "name": "用户角色", "type": "GBString", "code": "usrAut", "rules": [ { "message": "用户角色不允许为空", "name": "required" },{ "message": "用户权限只能为21|22|23", "name": "Auth" } ] },{ "name": "手机号码", "type": "Phone", "code": "usrMph", "rules": [ { "message": "手机号码不允许为空", "name": "required" },{ "message": "非法手机号", "name": "Phone" } ] },{ "name": "邮箱", "type": "Email", "code": "usrEml", "rules": [{ "message": "非法邮箱", "name": "Email" }]},{ "name": "备注", "type": "GBString", "code": "usrMmo" }]}
}

2、读取校验规则

​ 读取配置的json校验文件

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;/*** @author 陌上青花* @version 1.0 at 2020年11月17日*/
public class ParseJsonUtil {/*** entity map对象,key:name ,value:entity的属性map集**/public Map<String,Map<String,String>> entityMap;/*** column map 对象,key:entityName_colName , value:column的属性map集**/public Map<String,String> columnMap;/*** rule map 对象,key:entityName_colName_ruleName, value: rule 的map集:找到一行rule**/public Map<String,Map<String,String>> ruleMap;/*** rules map 对象, key:entityName_colName, value: rules 的map集:找到该column下所有的rule**/public Map<String,List<Map<String,String>>> columnRulesMap;/*** entity--column map: key:entityName, value: column list:根据实体类名得到所有的列**/public Map<String,JSONArray> columnListMap;public Map<String,Map<String,List<Map<String,String>>>> entityColumnRulesMap;/*** column list**/public List<Map<String,String>> columnList;/*** 构造函数** @param xmlFilePath json文件*/public ParseJsonUtil(File xmlFilePath) {/*对数据进行初始化设置*/int init = 16;columnListMap = new HashMap<>(init);columnMap = new HashMap<>(init);entityMap = new HashMap<>(init);ruleMap = new HashMap<>(init);entityColumnRulesMap = new HashMap<>(init);try {if (xmlFilePath == null) {throw new FileNotFoundException();}JSONObject jsonObject = JSONUtil.readJSONObject(xmlFilePath, CharsetUtil.CHARSET_UTF_8);Set<String> keySet = jsonObject.keySet();for (String key : keySet) {parseEntity(key, jsonObject);}} catch (Exception e) {e.printStackTrace();}}/*** 开始解析json** @param key 校验json文件key* @param jsonObject 校验json文件*/private void parseEntity(String key, JSONObject jsonObject) {if (jsonObject != null) {columnList = new ArrayList<>();columnRulesMap = new HashMap<>();columnMap = new HashMap<>();JSONObject excelJson = jsonObject.getJSONObject(key);String excelName = excelJson.getStr("name");JSONArray columnList = excelJson.getJSONArray("column");for (Object column : columnList) {setColumnMap(excelName, (JSONObject) column);}entityMap.put(key,columnMap);columnListMap.put(excelName, columnList);entityColumnRulesMap.put(excelName, columnRulesMap);}}/*** 将column放入columnMap中**/public void setColumnMap(String entityName, JSONObject column) {if (column != null) {HashMap<String,String> col = new HashMap<>();String name = column.getStr("name");String code = column.getStr("code");String type = column.getStr("type");col.put("name", name);col.put("code", code);col.put("type", type);columnMap.put(name, code);columnList.add(col);JSONArray rules = new JSONArray();if (column.containsKey("rules")) {rules = column.getJSONArray("rules");}for (Object rule : rules) {setRuleMap(entityName, name, (JSONObject) rule);}}}/*** 将 rule 验证规则放入ruleMap中**/public void setRuleMap(String entityName, String columnName, JSONObject ruleValid) {if (ruleValid != null) {String ruleName = ruleValid.getStr("name");String ruleMsg = ruleValid.getStr("message");HashMap<String,String> ruleValidMap = new HashMap<>();ruleValidMap.put("name", ruleName);ruleValidMap.put("message", ruleMsg);String ruleStrKey = entityName + "_" + columnName + "_" + ruleName;String colStrKey = entityName + "_" + columnName;if (this.getColumnRulesMap().containsKey(colStrKey)) {List<Map<String, String>> valid = this.getColumnRulesMap().get(colStrKey);valid.add(ruleValidMap);} else {List<Map<String, String>> valid = new ArrayList<>();valid.add(ruleValidMap);//将每个column下的所有rules存入该map中this.columnRulesMap.put(colStrKey, valid);}//将每个column下的一条rule存入该map中ruleMap.put(ruleStrKey, ruleValidMap);}}/*** 所有的get set 方法**/public Map<String,Map<String,String>> getEntityMap() {return entityMap;}/*** 将entity放入entityMap中** @param jsonObject 单个模板*/public void setEntityMap(JSONObject jsonObject) {HashMap<String,String> ent = new HashMap<>();String name = jsonObject.getStr("name");String code = jsonObject.getStr("code");ent.put("name", name);ent.put("code", code);entityMap.put(name, ent);}public void setEntityMap(Map<String, Map<String, String>> entityMap) {this.entityMap = entityMap;}public Map<String,  String> getColumnMap() {return columnMap;}public void setColumnMap(Map<String, String> columnMap) {this.columnMap = columnMap;}public Map<String, Map<String, String>> getRuleMap() {return ruleMap;}public void setRuleMap(Map<String, Map<String, String>> ruleMap) {this.ruleMap = ruleMap;}public Map<String, List<Map<String, String>>> getColumnRulesMap() {return columnRulesMap;}public void setColumnRulesMap(Map<String, List<Map<String, String>>> columnRulesMap) {this.columnRulesMap = columnRulesMap;}public Map<String, JSONArray> getColumnListMap() {return columnListMap;}public void setColumnListMap(Map<String, JSONArray> columnListMap) {this.columnListMap = columnListMap;}public Map<String, Map<String, List<Map<String, String>>>> getEntityColumnRulesMap() {return entityColumnRulesMap;}public void setEntityColumnRulesMap(Map<String, Map<String, List<Map<String, String>>>> entityColumnRulesMap) {this.entityColumnRulesMap = entityColumnRulesMap;}public List<Map<String, String>> getColumnList() {return columnList;}public void setColumnList(List<Map<String, String>> columnList) {this.columnList = columnList;}
}

3、校验Excel类

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.cell.CellUtil;
import com.cmb.midyjf.lu35.yjf.common.enums.ErrorEnum;
import com.cmb.midyjf.lu35.yjf.common.exception.ExcelUserException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;/*** 解析excel 工具类** @author 陌上青花*/
@SuppressWarnings("rawtypes")
public class ParseExcelUtil {public Workbook workBook;public ParseJsonUtil parseJsonUtil;public StringBuffer errorString;/*** 当前实体类的code**/public String curEntityCode;/*** 表头map对象:key:entityCode, value:headMap(index,headTitle)**/public Map curEntityHeadMap;/*** 字段的必填:key:entityCode+headTitle, value:true(必填),false(不必填)**/public Map curEntityColRequired;/*** 构造函数** @param workBook      workBook* @param parseJsonUtil 解析的校验json文件*/public ParseExcelUtil(Workbook workBook, ParseJsonUtil parseJsonUtil) {try {if (workBook == null) {throw new FileNotFoundException();}this.workBook = workBook;this.parseJsonUtil = parseJsonUtil;//readExcelData();} catch (FileNotFoundException e) {e.printStackTrace();}}/*** 构造函数** @param parseJsonUtil 解析的校验json文件*/public ParseExcelUtil(ParseJsonUtil parseJsonUtil) {this.parseJsonUtil = parseJsonUtil;}/*** 获得单元格字符串*/public static String getStringCellValue(Cell cell) {if (cell == null) {return null;}return String.valueOf(CellUtil.getCellValue(cell, true));}/*** 开始从excel读取数据**/public void readExcelData(String entityName) {errorString = new StringBuffer();int sheetSize = workBook.getNumberOfSheets();for (int i = 0; i < sheetSize; i++) {Sheet sheet = workBook.getSheetAt(i);//String entityName = workBook.getSheetName(i);readSheetData(sheet, entityName);}}/*** 读每个sheet页的数据**/public void readSheetData(Sheet sheet, String entityName) {readSheetHeadData(sheet);readSheetColumnData(sheet, entityName);}/*** 读取sheet页中的表头信息**/@SuppressWarnings({"unchecked", "static-access"})public void readSheetHeadData(Sheet sheet) {int init = 16;Map headMap = new HashMap(init);curEntityHeadMap = new HashMap(init);curEntityColRequired = new HashMap(init);Row excelHeadRow = sheet.getRow(0);int excelLastRow = excelHeadRow.getLastCellNum();for (int i = 0; i < excelLastRow; i++) {Cell cell = excelHeadRow.getCell(i);String headTitle = this.getStringCellValue(cell).trim();curEntityColRequired.put(this.getCurEntityCode() + "_" + headTitle, false);headMap.put(i, headTitle);}curEntityHeadMap.put(this.getCurEntityCode(), headMap);}/*** 读取sheet页里面的数据**/public void readSheetColumnData(Sheet sheet, String entityName) {Row excelHeadRow = sheet.getRow(0);//excel总列数int excelLastCell = excelHeadRow.getLastCellNum();//excel总行数int excelRowNum = sheet.getLastRowNum();Map headMap = (Map) this.getCurEntityHeadMap().get(this.getCurEntityCode());//行循环for (int i = 1; i < excelRowNum + 1; i++) {Row columnRow = sheet.getRow(i);//列循环if (!BeanUtil.isEmpty(columnRow)) {for (int j = 0; j < excelLastCell; j++) {String headTitle = headMap.get(j).toString();Cell colCell = columnRow.getCell(j);/*验证cell数据*/validateCellData(i + 1, j + 1, colCell, entityName, headTitle);}}}//如果没有任何错误,就保存if (this.getErrorString().length() > 0) {throw new ExcelUserException(ErrorEnum.EXCEL_ERROR.getErrCode(), errorString.toString());}}/*** 验证单元格数据**/@SuppressWarnings("static-access")public void validateCellData(int curRow, int curCol, Cell colCell, String entityName, String headName) {List<Map<String, String>> rulList = parseJsonUtil.getEntityColumnRulesMap().get(entityName).get(entityName + "_" + headName);if (rulList != null && rulList.size() > 0) {for (Map<String, String> rulM : rulList) {String rulName = rulM.get("name");String rulMsg = rulM.get("message");String cellValue = this.getStringCellValue(colCell);boolean flag = false;switch (rulName) {case ParseConstans.RULE_NAME_NULLABLE:if (StrUtil.isBlank(cellValue)) flag = true;break;case ParseConstans.RULE_NAME_IS_STRING:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isString(cellValue)) {flag = true;}break;case ParseConstans.RULE_NAME_IS_JF_STRING:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isJfString(cellValue)) {flag = true;}break;case ParseConstans.RULE_NAME_IS_N_STRING:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isnString(cellValue)) {flag = true;}break;case ParseConstans.RULE_NAME_IS_CURRENCY:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isCurrency(cellValue)) {flag = true;}break;case ParseConstans.RULE_NAME_IS_AREA:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isArea(cellValue)) {flag = true;}break;case ParseConstans.RULE_NAME_IS_PHONE:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isPhone(cellValue)) {flag = true;}break;case ParseConstans.RULE_NAME_IS_MAIL:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isMail(cellValue)) {flag = true;}break;case ParseConstans.RULE_NAME_IS_GB_STRING:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isGbString(cellValue)) {flag = true;}break;case ParseConstans.RULE_RANGE_LENGTH_32:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isStrLength32(cellValue)) {flag = true;}break;case ParseConstans.RULE_RANGE_LENGTH_64:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isStrLength64(cellValue)) {flag = true;}break;case ParseConstans.RULE_RANGE_LENGTH_11:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isStrLength11(cellValue)) {flag = true;}break;case ParseConstans.RULE_RANGE_LENGTH_2:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isStrLength2(cellValue)) {flag = true;}break;case ParseConstans.RULE_RANGE_LENGTH_4:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isStrLength4(cellValue)) {flag = true;}break;case ParseConstans.RULE_RANGE_LENGTH_16:if (!StrUtil.isBlank(cellValue) && !ValidatorUtil.isStrLength16(cellValue)) {flag = true;}break;default:break;}if (flag) {errorString.append("第").append(curRow).append("行,第").append(curCol).append("列:").append(rulMsg).append("<br>");}}}}public Workbook getWorkBook() {return workBook;}public void setWorkBook(Workbook workBook) {this.workBook = workBook;}public String getCurEntityCode() {return curEntityCode;}public void setCurEntityCode(String curEntityCode) {this.curEntityCode = curEntityCode;}public Map getCurEntityHeadMap() {return curEntityHeadMap;}public void setCurEntityHeadMap(Map curEntityHeadMap) {this.curEntityHeadMap = curEntityHeadMap;}public ParseJsonUtil getParseJsonUtil() {return parseJsonUtil;}public void setParseJsonUtil(ParseJsonUtil parseJsonUtil) {this.parseJsonUtil = parseJsonUtil;}public Map getCurEntityColRequired() {return curEntityColRequired;}public void setCurEntityColRequired(Map curEntityColRequired) {this.curEntityColRequired = curEntityColRequired;}public StringBuffer getErrorString() {return errorString;}public void setErrorString(StringBuffer errorString) {this.errorString = errorString;}}

4、单元格校验规则

import java.util.regex.Pattern;/*** @author 陌上青花* @version 1.0 at 2020年11月17日*/
public class ValidatorUtil {public static final String IS_STRING = "^[a-zA-Z0-9@.\\-]+\\d*$";public static final String IS_GB_STRING = "^(\\\\w*|\\\\W*|[\\\\u0391-\\\\uFFE5]*)*&";public static final String IS_GB_STRING_TB = "^[^'&<>\\\\\"/*]*$";public static final String IS_JF_STRING = "^[\\u0391-\\uFFE5a-zA-Z0-9\\-]+$";public static final String IS_N_STRING = "^[0-9]+\\d*$";public static final String IS_CURRENCY = "^([0-9]{1}\\d*)(\\.(\\d){1,2})?$";public static final String IS_AREA = "^([0-9]{1}\\d*)(\\.(\\d){1,2})?$";public static final String IS_PHONE = "^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\\d{8})$";public static final String IS_MAIL = "^([a-zA-Z0-9]+[-_.]*)*[a-zA-Z0-9]*@([a-zA-Z0-9]+[-_.]*)*[a-zA-Z0-9]+\\.[a-zA-Z]{2,3}$";/*** 校验是否是isString* @param string 待校验参数* @return 校验通过返回true,否则返回false*/public static boolean isString(String string){return Pattern.matches(IS_STRING, string);}/*** 校验是否是isGBString* @param string 待校验参数* @return 校验通过返回true,否则返回false*/public static boolean isGbString(String string){return Pattern.matches(IS_GB_STRING, string) && Pattern.matches(IS_GB_STRING_TB, string);}/*** 校验是否是isJFString* @param string 待校验参数* @return 校验通过返回true,否则返回false*/public static boolean isJfString(String string){return Pattern.matches(IS_JF_STRING, string);}/*** 校验是否是isNString* @param string 待校验参数* @return 校验通过返回true,否则返回false*/public static boolean isnString(String string){return Pattern.matches(IS_N_STRING, string);}/*** 校验是否是isCurrency* @param string 待校验参数* @return 校验通过返回true,否则返回false*/public static boolean isCurrency(String string){boolean maxbid = true;float f = (float) 9999999999999.99;if (Float.parseFloat(string)>f){maxbid = false;}return Pattern.matches(IS_CURRENCY, string)&& maxbid;}/*** 校验是否是isArea* @param string 待校验参数* @return 校验通过返回true,否则返回false*/public static boolean isArea(String string){boolean maxbid = true;float f = (float) 99999999.99;if(Float.parseFloat(string) > f){maxbid = false;}return Pattern.matches(IS_AREA, string) && maxbid;}/*** 校验是否是isPhone* @param string 待校验参数* @return 校验通过返回true,否则返回false*/public static boolean isPhone(String string){return Pattern.matches(IS_PHONE, string);}/*** 校验是否是isMail* @param string 待校验参数* @return 校验通过返回true,否则返回false*/public static boolean isMail(String string){return Pattern.matches(IS_MAIL, string);}}

5、配置规则常量

public class ParseConstans {public static final String RULE_NAME_NULLABLE = "required";public static final String RULE_NAME_IS_STRING = "String";public static final String RULE_NAME_IS_GB_STRING = "GBString";public static final String RULE_NAME_IS_JF_STRING = "JFString";public static final String RULE_NAME_IS_N_STRING = "NString";public static final String RULE_NAME_IS_CURRENCY = "Currency";public static final String RULE_NAME_IS_AREA = "Area";public static final String RULE_NAME_IS_PHONE = "Phone";public static final String RULE_NAME_IS_MAIL = "Mail";}

6、把ParseJsonUtil和ParseExcelUtil交给容器管理

@Configuration
public class SystemBeanCofig {@Value("${excel_check}")private String path;@Beanpublic ParseJsonUtil getParseJsonUtil() throws FileNotFoundException {File file = ResourceUtils.getFile(path);return new ParseJsonUtil(file);}@Beanpublic ParseExcelUtil getParseExcelUtil(ParseJsonUtil parseJsonUtil){return new ParseExcelUtil(parseJsonUtil);}
}

参考链接:https://blog.csdn.net/chenxuejiakaren/article/details/7764362

Excel单元格校验相关推荐

  1. 上传excel单元格校验(通过注解实现)

    ​ 业务上需求,前端上传excel到后端服务器,后端服务器解析excel,再把excel中的数据插入数据库中,再这个过程中,要对excel中的数据进行校验,所以就有了以下功能: ​ 该功能是基于策略+ ...

  2. python读取excel表格-Python读取Excel单元格的内容

    python读取excel的单元格返回类型 Python通过xlrd对Excel进行读取操作时,返回的数据类型(ctype)有下面5中类型: 0 – empty:空 1 – string:字符串 2 ...

  3. npoi 设置单元格不能修改_真巧妙!没密码也能解锁 Excel 单元格保护

    大家好,我是努力hard,本文要讨论的问题,在此摘要: ① Excel工作簿保护方式 ② 无密码解锁修改单元格 00 哥,这些单元格怎么不能点开 有个好友问我,下方图片的所有绿色区域都不能选中, 我很 ...

  4. 【Matlab】怎么修改Excel单元格颜色?

    1.Introduction 话说,当想把Matlab程序封装成一个完善的程序,那么输出展示是很重要的.所以最近想把输出的一组数据保存到Excel中,并自动把其中的指定数据给高亮.就像下面这样: 2. ...

  5. 为何excel中数据无法计算机,excel表格内数据为何无法计算机-为什么EXCEL单元格内的数字不能运算...

    我的电脑为什么不能把一个excel表中数据导入另一个... 在Excel中打不上去可能是由于数出了位数限制,对应及解决方下: 1.系统默认单元格中输入数字格式为"常规",能完全显示 ...

  6. java 读取 excel poi_java poi怎么获取excel单元格的内容?

    展开全部 package edu.sjtu.erplab.poi; import java.io.InputStream&ch=ww.xqy.chain" target=" ...

  7. java读取excel某个单元格的值_java poi怎么获取excel单元格的内容

    展开全部 package edu.sjtu.erplab.poi; import java.io.InputStream&ch=ww.xqy.chain" target=" ...

  8. python excel 单元格格式_python设置单元格数值格式

    python xlwt如何设置单元格格式 python xlwt模块怎么设置excel单元格的属性 如图,默认是general.我想写入的时候就是Text类型.请问应该怎么做. from xlwt i ...

  9. poi 不自动计算 设置单元格公式_Java POI:如何读取Excel单元格的值而不是计算公式?...

    上面的建议对我来说不起作用cell.getRawValue()返回与AUT上的excel单元格相同的公式,所以写下面的函数,它工作: public void readFormula() throws ...

最新文章

  1. 第一轮通知 | 2022年中国生物物理学会肠道菌群分会年会暨“崂山论肠菌”学术论坛...
  2. 云炬Android开发笔记 2-2 Android studio项目上传到Github及无法连接Github的问题处理
  3. [雪峰磁针石博客]大数据Hadoop工具python教程9-Luigi工作流...
  4. php zhegnze_php 正则表达式
  5. symbian系统开发教程(一)
  6. electron 桌面程序_如何使用Electron使用JavaScript构建您的第一个桌面应用程序
  7. 因程序问题引起的服务器CPU负荷一直保持在90%以上
  8. java2实用教程 第6版(课后习题总结)
  9. MathML学习:几个高等数学公式的MathML源码
  10. 怎么完整卸载mysql_如何完整卸载Mysql数据库
  11. leetcode之幂集(C++)
  12. web浏览器数据本地存储
  13. 这才是心理学:02可证伪性,如何打败头脑中的小精灵
  14. 云环境下搭建FTP服务器(不使用21端口)
  15. 社会会把你塑造成你讨厌的模样
  16. 常用地图投影转换公式 (转载)
  17. Java开发花三个月狂刷“面试宝典”成功从小厂35K跳槽到阿里50K
  18. 【数据挖掘】数据挖掘概述
  19. 如何在ORACLE数据库的字段上建立索引?
  20. 在k8s上安装Jenkins及常见问题

热门文章

  1. 四川一度智信|小白卖家不懂选品?
  2. 一度智信在拼多多上开店靠谱吗?
  3. 2022年双11淘宝满减规则解读
  4. 洗衣机程序c语言代码大全,全自动洗衣机控制器设计的单片机代码
  5. 【转】走火大神说:去年这时候又辞退了一个老油条,不知道他现在是否在开公司了,可以对比一下混工资的水平...
  6. B站投资,不务正业?
  7. 请问开发手机游戏需要什么软件?
  8. java c语言与人工智能_C语言与LISP语言的区别
  9. Mybatis + mysql获取元数据时出现问题以及解决
  10. Linux内存管理(四十):Linux PSI 详解