美文网首页
springboot导入excel文件并解析为entity

springboot导入excel文件并解析为entity

作者: 十九贝勒 | 来源:发表于2019-05-16 09:07 被阅读0次

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

    1、maven的pom文件添加依赖

            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi</artifactId>
                <version>RELEASE</version>
            </dependency>
            <dependency>
                <groupId>org.apache.poi</groupId>
                <artifactId>poi-ooxml</artifactId>
                <version>RELEASE</version>
            </dependency>
    

    2、excel导入工具类

    public static List<Object[]> importExcel(InputStream inputStream) {
            try {
                List<Object[]> 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<String,Object> resultMap,MultipartFile file) {
            if (file.isEmpty()) {
                return;
            }
    
            try {
                List<Object[]> 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

          本文链接:https://www.haomeiwen.com/subject/ieqbaqtx.html