SpringBoot系列之对Excel报表的校验提示

x33g5p2x  于2022-03-18 转载在 Spring  
字(2.0k)|赞(0)|评价(0)|浏览(601)

最近在做一个一对多excel类型的报表,如果excel报表数据填错了,要对其进行校验,然后返回给前端,做一个表格显示错误信息,excel报表数据读取的可以参考我上篇博客,链接

Excel格式类似于,维度是以合并单元行为准,如图,数据会读取到3条,然后有错误,就一行一行显示

错误信息类:

  1. package com.example.easyexcel.model.vo;
  2. import lombok.AllArgsConstructor;
  3. import lombok.Data;
  4. import lombok.ToString;
  5. import lombok.experimental.SuperBuilder;
  6. import javax.validation.constraints.NotBlank;
  7. import java.util.List;
  8. @Data
  9. @SuperBuilder(toBuilder = true)
  10. @AllArgsConstructor
  11. @NotBlank
  12. @ToString
  13. public class ExcelValidateError {
  14. private String index;
  15. private List<String> errMsgs;
  16. }

dto类,加上validation校验

  1. package com.example.easyexcel.model.dto;
  2. import com.alibaba.excel.annotation.ExcelProperty;
  3. import lombok.Data;
  4. import org.hibernate.validator.constraints.Length;
  5. import javax.validation.constraints.NotBlank;
  6. @Data
  7. public class UserExcelDto {
  8. private String index;
  9. @ExcelProperty(value = "序号",index = 0)
  10. @NotBlank(message = "序号必须填!")
  11. private String seq;
  12. @ExcelProperty(value = "用户名" ,index = 1)
  13. @NotBlank(message = "用户名必须填!")
  14. private String name;
  15. @ExcelProperty(value = "密码", index = 2)
  16. @Length(min = 0 , max = 8 , message = "密码最多8位!")
  17. @NotBlank(message = "密码必须填!")
  18. private String password;
  19. @ExcelProperty(value = "描述",index = 3)
  20. @NotBlank(message = "地址描述必须填!")
  21. private String addressName;
  22. @ExcelProperty(value = "邮政编码",index = 4)
  23. @NotBlank(message = "邮政编码必须填!")
  24. private String code;
  25. }

封装读取校验数据

  1. @Autowired
  2. private Validator validator;
  3. private List<ExcelValidateError> doValidateExcel(final List<UserExcelDto> excelDtoList) {
  4. final List<ExcelValidateError> errs = new ArrayList<ExcelValidateError>();
  5. if (!excelDtoList.isEmpty()) {
  6. excelDtoList.stream().forEach(dto->{
  7. Set<ConstraintViolation<UserExcelDto>> violations = validator.validate(dto);
  8. List<String> errMsgs = new ArrayList<>();
  9. if (!violations.isEmpty()) {
  10. errMsgs = violations.stream().map(e -> e.getMessage()).collect(Collectors.toList());
  11. }
  12. if (!errMsgs.isEmpty()) {
  13. errs.add(ExcelValidateError
  14. .builder()
  15. .index(dto.getIndex())
  16. .errMsgs(errMsgs)
  17. .build());
  18. }
  19. });
  20. }
  21. return errs;
  22. }

相关文章