EasyExcel导入校验返回错误信息,不影响正确信息读入

问题需求

从excel导入批量数据插入数据库,校验格式后将有错误的信息返回,正确无误的数据插入数据库。

问题相关代码

实体DO

public class ToolStockDO implements Serializable {
    private static final long serialVersionUID = 1L;
    /**
     * 工器具id
     */
    @ExcelIgnore
    @TableId(type = IdType.AUTO)
    @ApiModelProperty(value = "工器具id")
    private Long toolId;
    /**
     * 所属仓库id
     */
    @ExcelIgnore
    @ApiModelProperty(value = "所属仓库id")
    private Long warehouseId;
    /**
     * 所属仓库名称
     */
    @ExcelIgnore
    @ApiModelProperty(value = "所属仓库名称")
    @NotBlank(message="仓库名称不能为空")
    private String warehouseName;
}

业务service

public Result upload(MultipartFile file,Long warehouseId){
        Result result = Result.ok();
        try {
            List<ToolStockDO> list = ExcelUtil.syncReadModel(file.getInputStream(), ToolStockDO.class, 0, 1);
            try{
                result = this.save(list,warehouseId);
            }catch (Exception e){
                e.printStackTrace();
                return Result.error("存入数据库失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("校验失败(数据格式错误)");
        }
        return result;
    }
运行结果

这种方式在遇到校验不合格的数据会停止导入,不能继续读取合格的数据。

具体的关键在于save方法,改造这个方法捕获异常,然后继续处理下一条就可以了

https://blog.csdn.net/XuDream/article/details/122108217 看一下这个