springboot导入excel文件并解析为entity

好久没写了,写一下最近用到的导入excel文件的功能吧

1、maven的pom文件添加依赖

        
            org.apache.poi
            poi
            RELEASE
        
        
            org.apache.poi
            poi-ooxml
            RELEASE
        

2、excel导入工具类

public static List importExcel(InputStream inputStream) {
        try {
            List list = new ArrayList<>();
            Workbook workbook = WorkbookFactory.create(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            //获取sheet的行数
            int rows = sheet.getPhysicalNumberOfRows();
            for (int i = 0; i < rows; i++) {
                //过滤表头行
                if (i == 0) {
                    continue;
                }
                //获取当前行的数据
                Row row = sheet.getRow(i);
                Object[] objects = new Object[row.getPhysicalNumberOfCells()];
                int index = 0;
                for (Cell cell : row) {

                    if (cell.getCellType().equals(NUMERIC)) {
                        objects[index] = numberFormat.format(cell.getNumericCellValue());
                    }
                    if (cell.getCellType().equals(STRING)) {
                        objects[index] = cell.getStringCellValue();
                    }
                    if (cell.getCellType().equals(BOOLEAN)) {
                        objects[index] = cell.getBooleanCellValue();
                    }
                    if (cell.getCellType().equals(ERROR)) {
                        objects[index] = cell.getErrorCellValue();
                    }
                    index++;
                }
                list.add(objects);
            }
            log.info("导入文件解析成功!");
            return list;
        }catch (Exception e){
            log.info("导入文件解析失败!");
            e.printStackTrace();
        }
        return null;
    }

3、前端导入按钮(本人使用的是layui)

layui.use(['form', 'layedit','upload', 'excel','laydate'], function () {
    upload.render({
        elem: '#uploadFile' //缁戝畾鍏冪礌
        ,accept:'file'
        ,exts:'xls|xlsx'
        ,url: '/board/upload' //涓婁紶鎺ュ彛
        ,type: 'post'
        ,done: function(res){
            layerTips.msg(res.msg);
            apply.table.bootstrapTable('refresh', apply.queryParams());
        }
        ,error: function(){
            //璇锋眰寮傚父鍥炶皟
            layerTips.msg("上传失败");
        }
    });
});

4、后台处理

public Map upload(@RequestParam("file") MultipartFile file) {
        return baseBiz.upload(file);
}

public Map upload(MultipartFile file){
        Map resultMap = new HashMap();
        if (file != null) {
            saveFile(resultMap,file);
            if (resultMap.get("code").equals("0")) {
                Map fileMap = new HashMap();
                fileMap.put("src", "");
                resultMap.put("data", fileMap);
                return resultMap;
            } else {
                return resultMap;
            }
        }
        return resultMap;
    }

    public void saveFile( Map resultMap,MultipartFile file) {
        if (file.isEmpty()) {
            return;
        }

        try {
            List objects = ExcelUtil.importExcel(file.getInputStream());

            for (Object[] os : objects) {
                MessageBoard entity=MessageBoard.builder().id(Long.parseLong(String.valueOf(os[0]))).telphone(String.valueOf(os[1])).message(String.valueOf(os[2])).build();
                if(selectById(entity.getId())==null){
                    insertSelective(entity);
                }else{
                    updateSelectiveById(entity);
                }
            }

            resultMap.put("filename", file.getOriginalFilename());
            resultMap.put("saveUrl", "");
            resultMap.put("code", "0");
            resultMap.put("msg", "导入成功!");
            return ;
        } catch (Exception e) {
            e.printStackTrace();
            resultMap.put("code", "-2");
            resultMap.put("msg", "导入异常!");
            return ;
        }
    }

至此导入工作已经完成,到数据库核对数据是否导入正常即可

你可能感兴趣的:(springboot导入excel文件并解析为entity)