注解类:
@Retention(RetentionPolicy.RUNTIME) public @interface ExcelValidate { public boolean ignoreBlank() default false; public int max() default Integer.MAX_VALUE; public int min() default 0; public boolean notNull() default false; public String format() default ""; }
被注解类:
public class ExcelAssetsBusinessVO { @ExcelValidate(notNull=true,max=100) private String name; @ExcelValidate(notNull=true) private String ip; private String port; }
注解解析工具:
public class ExcelValidateUtil { public static <E> List<String> check(List<E> list, int index) throws Exception { List<String> strList = new ArrayList<>(); Iterator<E> it = list.iterator(); int i = 0; while(it.hasNext()) { int offset = i + index; E e = it.next(); Field[] fields = e.getClass().getDeclaredFields(); //对excel中的空行进行校验 int count = 0, step = 0; ExcelValidate excelValidateClass = e.getClass().getAnnotation(ExcelValidate.class); if (excelValidateClass.ignoreBlank()) { for (Field field : fields) { count++; field.setAccessible(true); if (field.get(e) == null || StringUtils.isBlank(field.get(e).toString())) { step++; } } } if (count == step) { it.remove(); continue; } for (Field field : fields) { field.setAccessible(true); if (field.isAnnotationPresent(ExcelValidate.class)) { ExcelValidate excelValidate = field.getAnnotation(ExcelValidate.class); ExcelField excelField = field.getAnnotation(ExcelField.class); if (excelValidate.notNull()) { if (field.get(e) == null || field.get(e).toString().trim().length() == 0) { String str = "第" + offset + "行," + excelField.title().substring(0, excelField.title().length()-1) + "不能为空!"; strList.add(str); continue; } } if (excelValidate.max() != Integer.MAX_VALUE) { if (field.get(e)!=null && field.get(e).toString().length() > excelValidate.max()) { String str = ""; if(excelField.title().endsWith("*")) { str = "第" + offset + "行," + excelField.title().substring(0, excelField.title().length()-1) + "不能超过" + excelValidate.max() + "字符!"; }else { str = "第" + offset + "行," + excelField.title() + "不能超过" + excelValidate.max() + "字符!"; } strList.add(str); continue; } } if (excelValidate.min() != 0) { if (field.get(e)!=null && field.get(e).toString().length() < excelValidate.min()) { String str = ""; if(excelField.title().endsWith("*")) { str = "第" + offset + "行," + excelField.title().substring(0, excelField.title().length()-1) + "不能少于" + excelValidate.max() + "字符!"; }else { str = "第" + offset + "行," + excelField.title() + "不能少于" + excelValidate.max() + "字符!"; } strList.add(str); continue; } } if (field.get(e)!=null && !"".equals(excelValidate.format())) { boolean valid = Pattern.matches(excelValidate.format(), field.get(e).toString()); if (!valid) { String str = ""; if(excelField.title().endsWith("*")) { str = "第" + offset + "行," + excelField.title().substring(0, excelField.title().length()-1) + "格式不正确!"; } else { str = "第" + offset + "行," + excelField.title() + "格式不正确!"; } strList.add(str); continue; } } } } i++; } return strList; } }