EasyExcel上传校验文件错误信息放到文件里以Base64 返回给前端
产品需求:
前端上传个csv 或 excel 文件,文件共4列,验证文件大小,类型,文件名长度,文件内容,如果某行某个单元格数据验证不通过,就把错误信息放到这行第五列,然后把带有错误信息的文件,返回给前端。
@ApiOperation(value = "上传新增")
@PostMapping(path = "uploadFile")
public ResultMsg<?> uploadExcelFile(@RequestParam("file") MultipartFile file) throws IOException {
if (file.getOriginalFilename().length() > 256) {
return ResultMsg.failed("文件名超长");
}
if (file.getSize() > 3 * 1024 * 1024) {
return ResultMsg.failed("文件太大");
}
String fileType = Optional.ofNullable(file.getOriginalFilename())
.map(name -> name.substring(name.lastIndexOf(".")))
.orElse(null);
if (!".xls".equalsIgnoreCase(fileType) && !".xlsx".equalsIgnoreCase(fileType) && !".csv".equalsIgnoreCase(fileType)) {
return ResultMsg.failed("仅支持 [xls xlsx csv] 格式");
}
StyleOfWritingExcelDTO dto = null;
try {
dto = this.validateAndReadExcel(file.getInputStream());
} catch (IOException e) {
throw new RuntimeException(e);
}
if (dto.getHasError()) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
EasyExcel.write(byteArrayOutputStream, StyleOfWritingExcelModel.class)
// .excelType(ExcelTypeEnum.XLSX)
.sheet("sheet1")
.doWrite(dto.getStyleOfWritingExcelModelList());
String base64Str = Base64.getEncoder().encodeToString(byteArrayOutputStream.toByteArray());
Map<Object, Object> base64Map = new HashMap<>();
base64Map.put("errStr", "文件内容不合格");
base64Map.put("fileData", base64Str);
return ResultMsg.failed(4001, "文件内容不合格", base64Map);
}
if (dto.getStyleOfWritingExcelModelList().isEmpty()) return ResultMsg.failed("文件内容为空");
saveData(dto.getStyleOfWritingExcelModelList());
return ResultMsg.success();
}
private StyleOfWritingExcelDTO validateAndReadExcel(InputStream inputStream) {
StyleOfWritingExcelDTO result = new StyleOfWritingExcelDTO();
List<StyleOfWritingExcelModel> dataList = new ArrayList<>();
EasyExcel.read(inputStream, StyleOfWritingExcelModel.class, new AnalysisEventListener<StyleOfWritingExcelModel>() {
@Override
public void invoke(StyleOfWritingExcelModel styleOfWritingExcelModel, AnalysisContext analysisContext) {
StringBuilder errorInfo = new StringBuilder();
CategoryEntity firstCategory = null;
if (StringUtils.isBlank(styleOfWritingExcelModel.getFirstCategoryName())) {
errorInfo.append("品类不能为空;");
} else if (styleOfWritingExcelModel.getFirstCategoryName().length() > 50) {
errorInfo.append(String.format("品类名长度超限,限制最大[%d]字符;", 50));
} else {
firstCategory = this.getCategoryCode(styleOfWritingExcelModel.getFirstCategoryName());
if (ObjectUtils.isEmpty(firstCategory))
errorInfo.append(String.format("品类在库里未找到;"));
else
styleOfWritingExcelModel.setFirstCategory(firstCategory.getCode());
}
CategoryEntity secondCategory = null;
if (StringUtils.isBlank(styleOfWritingExcelModel.getSecondCategoryName())) {
errorInfo.append("二级品类不能为空; ");
} else if (styleOfWritingExcelModel.getSecondCategoryName().length() > 50) {
errorInfo.append(String.format("二级品类名长度超限,限制最大[%d]字符", 50));
} else {
secondCategory = this.getCategoryCode(styleOfWritingExcelModel.getSecondCategoryName());
if (ObjectUtils.isEmpty(secondCategory))
errorInfo.append(String.format("二级品类在库里未找到;"));
else
styleOfWritingExcelModel.setSecondCategory(secondCategory.getCode());
}
if (ObjectUtils.isNotEmpty(firstCategory) && ObjectUtils.isNotEmpty(secondCategory)) {
if (!firstCategory.getCode().equals(secondCategory.getParentCode())) {
errorInfo.append(String.format("二级品类 和 品类 不匹配"));
}
}
if (StringUtils.isBlank(styleOfWritingExcelModel.getContent())) {
errorInfo.append("内容不能为空; ");
} else if (styleOfWritingExcelModel.getContent().length() > 3000) {
errorInfo.append(String.format("内容长度超限,限制最大[%d]字符", 3000));
}
styleOfWritingExcelModel.setErrorInfo(errorInfo.toString());
dataList.add(styleOfWritingExcelModel);
if (!result.getHasError() && StringUtils.isNotBlank(errorInfo.toString())) {
result.setHasError(true);
}
}
private CategoryEntity getCategoryCode(String categoryName) {
List<CategoryEntity> categoryList = categoryService.list(new QueryWrapper<CategoryEntity>().lambda().eq(CategoryEntity::getName, categoryName));
return categoryList.stream()
.findFirst()
.orElse(null);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 解析完成后的操作
}
}).sheet().doRead();
result.setStyleOfWritingExcelModelList(dataList);
return result;
}
返回:
{
"code": 4001,
"message": "文件内容不合格",
"data": {
"fileData": "UEsDBC0ACAAIAAAAAAAAAAAAAAAAAAAAAAATAAAAW0NvbnRlbnRfVHlwZXNdLnhtbLVTy27CMBD8lcjXKjb0UFUVgUMfxxap9ANce5NY+CWvofD3XQc4lFKJCnHyY2ZnZlf2ZLZxtlpDQhN8w8Z8xCrwKmjju4Z9LF7qe1Zhll5LGzw0bAvIZtPJYhsBK6r12LA+5/ggBKoenEQeInhC2pCczHRMnYhSLWUH4nY0uhMq+Aw+17losOnkCVq5srl63N0X6YbJGK1RMlMssfb6SLTeC/IEduBgbyLeEIFVzxtS2bVDKDJxhsNxYTlT3RsNJhkN/4oW2tYo0EGtHJVwKKoadB0TEVM2sM85lym/SkeCgshzQlGQNL/E+zAWFRKcZViIFzkedYsxgdTYA2RnOfYygX7PiV7T7xAbK34Qrpgjb+2JKZQAA3LNCdDKnTT+lPtXSMvPEJbX8y8Ow/4v+wFEMSzjQw4xfO/pN1BLBwiRLCi8OwEAAAAAAAAdBAAAAAAAAFBLAwQtAAgACAAAAAAAAAAAAAAAAAAAAAAACwAAAF9yZWxzLy5yZWxzrZLBSgMxEIZfJcy9m20FEWnaiwi9idQHGJPZ3bCbTEhG3b69wYu2bEHB4zAz3/8xyXY/h0m9Uy6eo4F104KiaNn52Bt4OT6u7kAVwehw4kgGTlRgv9s+04RSV8rgU1GVEYuBQSTda13sQAFLw4li7XScA0otc68T2hF70pu2vdX5JwPOmergDOSDW4M6Yu5JDMyT/uA8vjKPTcXWxinRb0K567ylB7ZvgaIsZF9MgF522Xy7OLZPmesmpvTfMjQLRUdulWoCZfH14leMbhaMLGf6m9L1R9GBBB0KflEvhPTZH9h9AlBL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