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

2022-05-07 18:16:58 浏览数 (1)

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

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

错误信息类:

代码语言:javascript复制
package com.example.easyexcel.model.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.ToString;
import lombok.experimental.SuperBuilder;

import javax.validation.constraints.NotBlank;
import java.util.List;

@Data
@SuperBuilder(toBuilder = true)
@AllArgsConstructor
@NotBlank
@ToString
public class ExcelValidateError {

    private String index;

    private List<String> errMsgs;

}

dto类,加上validation校验

代码语言:javascript复制
package com.example.easyexcel.model.dto;

import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotBlank;


@Data
public class UserExcelDto {

    private String index;

    @ExcelProperty(value = "序号",index = 0)
    @NotBlank(message = "序号必须填!")
    private String seq;

    @ExcelProperty(value = "用户名" ,index = 1)
    @NotBlank(message = "用户名必须填!")
    private String name;

    @ExcelProperty(value = "密码", index = 2)
    @Length(min = 0 , max = 8 , message = "密码最多8位!")
    @NotBlank(message = "密码必须填!")
    private String password;

    @ExcelProperty(value = "描述",index = 3)
    @NotBlank(message = "地址描述必须填!")
    private String addressName;

    @ExcelProperty(value = "邮政编码",index = 4)
    @NotBlank(message = "邮政编码必须填!")
    private String code;



}

封装读取校验数据

代码语言:javascript复制
@Autowired
private Validator validator;

private List<ExcelValidateError> doValidateExcel(final List<UserExcelDto> excelDtoList) {
    final List<ExcelValidateError> errs = new ArrayList<ExcelValidateError>();
    if (!excelDtoList.isEmpty()) {
        excelDtoList.stream().forEach(dto->{
            Set<ConstraintViolation<UserExcelDto>> violations = validator.validate(dto);
            List<String> errMsgs = new ArrayList<>();
            if (!violations.isEmpty()) {
                errMsgs = violations.stream().map(e -> e.getMessage()).collect(Collectors.toList());
            }
            if (!errMsgs.isEmpty()) {
                errs.add(ExcelValidateError
                        .builder()
                        .index(dto.getIndex())
                        .errMsgs(errMsgs)
                        .build());
            }
        });

    }
    return errs;
 
}

0 人点赞