EasyExcel文件导入
导入对象定义(设置标题头模板)
public class AppInfoAuthMachineExcelDTO {
@ExcelProperty(value = "机器名称")
@NotBlank(message = "机器名称不能为空")
private String machineName;
@ExcelProperty(value = "机器码")
@NotBlank(message = "机器码不能为空")
private String machineCode;
public String getMachineName() {
return machineName;
}
public void setMachineName(String machineName) {
this.machineName = machineName;
}
public String getMachineCode() {
return machineCode;
}
public void setMachineCode(String machineCode) {
this.machineCode = machineCode;
}
}
导入监听器(异常处理与数据处理)
public class AppInfoAuthMachineImportListener extends AnalysisEventListener<AppInfoAuthMachineExcelDTO> {
private static final Logger logger = LoggerFactory.getLogger(AppInfoAuthMachineImportListener.class);
private final List<AppInfoAuthMachineExcelDTO> result;
public AppInfoAuthMachineImportListener(List<AppInfoAuthMachineExcelDTO> result) {
this.result = result;
}
@Override
public void onException(Exception e, AnalysisContext analysisContext) {
logger.error("文件导入解析失败,失败原因:", e);
String exceptionMsg = ExceptionUtils.parseException(e);
if (e instanceof ExcelDataConvertException) {
ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) e;
exceptionMsg = "导入文件解析失败,第" + (excelDataConvertException.getRowIndex() + 1) + "行,第" + (excelDataConvertException.getColumnIndex() + 1) + "列数据解析异常,数据为"
+ excelDataConvertException.getCellData().getStringValue() + ",失败原因:" + parseExceptionMsg(e);
}
throw new BusinessException(CommonEnums.BUSINESS_ERROR, exceptionMsg);
}
private String parseExceptionMsg(Exception e) {
if (StringUtils.contains(e.getMessage(), "to class java.time.LocalDate error")) {
return "时间格式错误!";
}
if (StringUtils.contains(e.getMessage(), "to class java.math.BigDecimal error")) {
return "数字格式错误!";
}
return ExceptionUtils.parseException(e);
}
@Override
public void invokeHead(Map<Integer, CellData> map, AnalysisContext analysisContext) {
Field[] fields = AppInfoAuthMachineExcelDTO.class.getDeclaredFields();
List<String> tempHeadList = Arrays.stream(fields)
.filter(field -> Objects.nonNull(field.getAnnotation(ExcelProperty.class)))
.map(field -> CollectionUtils.firstElement(Arrays.asList(field.getAnnotation(ExcelProperty.class).value())))
.collect(Collectors.toList());
List<String> fileHeadList = map.values().stream().map(CellData::getStringValue).collect(Collectors.toList());
if (!fileHeadList.containsAll(tempHeadList)) {
tempHeadList.removeAll(fileHeadList);
logger.error("文件导入校验失败,失败原因: {}[{}]", "导入文件与系统模板不匹配,缺少标题头", String.join(", ", tempHeadList));
throw new BusinessException(CommonEnums.BUSINESS_ERROR,
String.format("Excel文件读取失败,失败原因: 导入文件与系统模板不匹配,缺少标题头[%s]",String.join(", ", tempHeadList)));
}
}
@Override
public void invoke(AppInfoAuthMachineExcelDTO data, AnalysisContext context) {
String errMsgPrefix = "导入文件读取失败, 第" + context.readRowHolder().getRowIndex() + "行数据异常";
ValidatorUtil.validate(data, errMsgPrefix);
result.add(data);
}
@Override
public void extra(CellExtra cellExtra, AnalysisContext analysisContext) {
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
}
}
Service使用
public List<AppInfoAuthMachineExcelDTO> parseAppInfoMachineExcel(MultipartFile file) {
List<AppInfoAuthMachineExcelDTO> result = new ArrayList<>();
try {
EasyExcel.read(file.getInputStream(), AppInfoAuthMachineExcelDTO.class, new AppInfoAuthMachineImportListener(result))
.sheet()
.headRowNumber(1)
.doRead();
} catch (IOException e) {
throw new BusinessException(CommonEnums.BUSINESS_ERROR, msg -> "Excel文件读取失败", e);
}
if (CollectionUtils.isEmpty(result)) {
throw new BusinessException(CommonEnums.BUSINESS_ERROR, "应用授权机器导入数据为空");
}
return result;
}
字段校验工具类
public class ValidatorUtil {
private static final Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
public static void validate(Object obj, String errMsgPrefix) {
Map<String, String> validMsg = new LinkedHashMap<>();
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(obj);
for (ConstraintViolation<Object> c : constraintViolations) {
validMsg.put(c.getPropertyPath().toString(), c.getMessage());
}
if (ObjectUtils.isNotEmpty(constraintViolations)) {
throw new BusinessException(CommonEnums.BUSINESS_ERROR, errMsgPrefix + " " + validMsg.values().toString());
}
}
}