easypoi 校验导入excel 将校验不通过字段返回
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.afterturn.easypoi.excel.entity.result.ExcelVerifyHandlerResult;
import cn.afterturn.easypoi.handler.inter.IExcelVerifyHandler;
import java.io.File;
import java.util.List;
public class ExcelVerifyDemo {
public static void main(String[] args) {
// 指定Excel文件路径
String filePath = "path/to/your/excel/file.xlsx";
// 导入Excel数据
ImportParams params = new ImportParams();
params.setTitleRows(1);
params.setHeadRows(1);
params.setVerifyHandler(new MyVerifyHandler()); // 设置自定义校验处理器
List<ExcelData> dataList = ExcelImportUtil.importExcel(new File(filePath), ExcelData.class, params);
// 处理校验结果
for (ExcelData data : dataList) {
if (data.getVerifyResult() != null && !data.getVerifyResult().isSuccess()) {
System.out.println("校验不成功的数据:" + data);
}
}
}
// 定义Excel数据模型类
public static class ExcelData {
// 标记需要校验的字段
@NotNull
private String columnA;
@Length(min = 5, max = 10, message = "B列长度应在5到10之间")
private String columnB;
// 校验结果对象
private ExcelVerifyHandlerResult verifyResult;
// 省略 getter 和 setter 方法
}
// 自定义校验处理器
public static class MyVerifyHandler implements IExcelVerifyHandler<ExcelData> {
@Override
public ExcelVerifyHandlerResult verifyHandler(ExcelData obj) {
ExcelVerifyHandlerResult result = new ExcelVerifyHandlerResult();
// 进行自定义校验
if (obj.getColumnA() == null || obj.getColumnA().isEmpty()) {
result.setSuccess(false);
result.setMsg("A列不能为空");
}
if (obj.getColumnB() != null && obj.getColumnB().length() < 5) {
result.setSuccess(false);
result.setMsg("B列长度不能小于5");
}
// 设置校验结果对象
obj.setVerifyResult(result);
return result;
}
}
}
pom依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.2.0</version>
</dependency>