《 工作呀工作 之 excel 上传 》

上传excel 解析内容入库完成以后,测试反馈说缺乏校验。

就是excel 的内容,缺乏校验。如果内容不符合我们的要求,应该告诉用户xx行 内容有误

 

实现:

1、使用了自定义异常,解析出现问题时向上抛出

2、自定义结果,在service 返回这个结果,controller 中判断结果,如果获取msg 给前台

 

* 自定义异常

public class ExcelParseException extends RuntimeException {

    /** serialVersionUID*/
    private static final long serialVersionUID = 1L;

    private String msg;

    public ExcelParseException(String msg) {
        super();
        this.msg = msg;
    }

 

参数需要一个msg 错误信息

 

* 结果类

    public class ExcelResult {

    private boolean flag;
    private String msg;

    public static ExcelResult result(boolean flag,String msg){
        return new ExcelResult(flag, msg);
    }
    
    public ExcelResult(boolean flag, String msg) {
        this.flag = flag;
        this.msg = msg;
    }

 

只需要msg  和 flag 即可,然后提供静态方法 返回对象

 

* service

    @Override
    public ExcelResult dataImport(MultipartFile file) {
        String msg ="";
        boolean flag = true;

for (int i = begin; i <= end; i++) {
                Row row = oFirstSheet.getRow(i);
                if (!ToolUtils.isRowEmpty(row)) {
                    RiskConfigure risk = new RiskConfigure();
                    for (int j = 0; j < 8; j++) {// 8列
                        Cell oCell = row.getCell(j);
                        String str = ToolUtils.getCellValue(oCell);
                        if (!"".equals(str)) {// 判断单元格是否为空
                            switch (j) {
                            case 0:
                                if(!str.equals("nba")){
                                    throw new ExcelParseException("第" +i + "行数据有误");
                                }
                                risk.setFpc(str);// 分销商代码
                                break;

} catch (ExcelParseException e) {
  flag = false;
  msg = e.getMsg();
  e.printStackTrace();
} catch (Exception e) {
  flag = false;
  msg = "服务器内部出现异常";
  e.printStackTrace();
}
return ExcelResult.result(flag, msg);

 

开始的时候定义msg flag 

然后当某一行出现问题时,抛出异常,这样方法结束了,然后set msg的值

if(!str.equals("nba")){
        throw new ExcelParseException("第" +i + "行数据有误");
   }

然后 

flag = false;  表示执行失败
  msg = e.getMsg();  

最后return 

 

Controller

    @ApiOperation("导入风险配置数据")
    @PostMapping(value = "/dataImport")
    public ResponseEntity<String> dataImport(MultipartFile file) {
        
        ExcelResult result = riskConfigureService.dataImport(file);
        if(result.isFlag()){
            return new ResponseEntity<>(HttpStatus.OK);
        } else {
            return new ResponseEntity<>(result.getMsg(),HttpStatus.FAILED_DEPENDENCY);
        }
    }

判断结果,返回给前台

 

测试

 

Response Body

第1行数据有误

 

posted @ 2018-05-30 14:28  lyon♪♫  阅读(139)  评论(0编辑  收藏  举报