通常在导入excel数据做逻辑处理时,会有需要校验字段必填的场景,一般可以通过自定义注解、或者工具类方法的方式进行校验
校验excel中字段必填
/**
* 判断对象中对应字段值是否不为空
* @param t 对象
* @param i 表示excel的行数
* @param checkArr 需要校验字段的数组
*/
public static <T> String checkExcel(T exportInfo, int i,String ... checkArr){
String check = "";
if(t == null){
throw new SystemException("t is not allow null value");
}
Class tClass = t.getClass();
Field[] fields = tClass.getDeclaredFields();
List<String> checkList = Arrays.asList(checkArr);
for(Field f : fields){
if(checkList.contains(f.getName())){
//cn.hutool.core.bean.BeanUtil
if(StringUtils.isEmpty(BeanUtil.getFieldValue(t, f.getName()))){
check = "</br>第"+(i+2)+"行存在必填项未填写;";
break;
}
}
}
return check;
}
调用片段:
StringBuffer errorMessageList = new StringBuffer();//异常信息
List list = listener.getDatas(); String[] checkArr=new
String[]{“id”,“name”};//需要校验的属性 for (int i = 0; i < list.size(); i++)
{ String message=checkExcel(exportInfo,i,checkArr);
if (StringUtils.isNotBlank(needmsg)) {
errorMessageList.append(needmsg);
continue;
} }
校验excel中字段必填,所有包含ExcelProperty注释的字段都需要校验,checkList 则代表不需要校验的字段,与上面方法相反。
/**
* 反向判断对象中对应字段值是否不为空 ,字段注解使用了ExcelProperty,且不在checkList,进行校验,主要用于对象字段基本都需要校验的场景
* @param t 对象,
* @param checkList 不需要校验字段名的数组
*/
public static <T> String checkFileidNotContain(T t,List<String> checkList){
String check = "";
if(t == null){
throw new SystemException("t is not allow null value");
}
Class tClass=t.getClass();
for(Field f:tClass.getDeclaredFields()){
ExcelProperty ep = f.getAnnotation(ExcelProperty.class);//字段需要有这个注解才进行校验
if(ep==null){
continue;
}
if(checkList!=null&&checkList.contains(f.getName())){//字段在list中的也不需要校验
continue;
}
//cn.hutool.core.bean.BeanUtil
if(StringUtils.isEmpty(BeanUtil.getFieldValue(t, f.getName()))){
// @ExcelProperty(value = "机构")
//check = ep.value()[0];//ExcelProperty注释的value值
check ="</br>第"+(i+2)+"行字段"+ ep.value()[0]+"存在必填项未填写或者未按照下拉选项值填写;";
break;
}
}
return check;
}