当前位置:   article > 正文

Layui表格按JSON格式导入导出_layui读取本地json数据

layui读取本地json数据
前端代码
  1. html

    <div id="importFieldCatalog" class="layui-btn layui-btn-sm layui-btn-primary">
        导 入
    </div>
    <div id="exportFieldCatalog" class="layui-btn layui-btn-sm layui-btn-primary">
        导 出
    </div>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
  2. js

    var table, form, layer;
    var layerFieldCatalogQuery = {}; // 图层字段目录列表过滤条件
    var selectedIdList = []; // 所有选中的图层字段目录id列表
    ...
    
    layui.use(['table', 'form', 'layer', 'upload'], function () {
        table = layui.table,
            form = layui.form,
            layer = layui.layer,
            upload = layui.upload
        ...
        monitor();
        ...
    });
    
    /**
     * 监听事件
     */
    function monitor() {
        ...
        upload.render({
            elem: '#importFieldCatalog',
            url: resBaseUrl + '/dict/importLayerField',
            accept: 'file',
            auto: true,
            acceptMime: 'application/json',
            exts: 'json',
            before: function () {
                this.data = {
                    parentId: layerFieldCatalogQuery.parentId,
                }
            },
            done: function (res) {
                if (res.success) {
                    layer.msg("导入成功", {icon: 1, time: 1500});
                    initLayerFieldCatalogTable();
                } else {
                    layer.msg(res.message, {icon: 2, time: 1500});
                }
            }
        });
    
        $("#exportFieldCatalog").click(function () {
            selectedIdList = [];
            var selectedList = table.checkStatus('layerFieldCatalogID').data;
            if (selectedList.length > 0) {
                selectedIdList = selectedList.map((item) => {
                    return item.id;
                })
            }
            postDataToServer('/dict/exportLayerField?parentId=' + layerFieldCatalogQuery.parentId, JSON.stringify(selectedIdList), function (res) {
                if (res.success) {
                    var filename = "图层字段导出文件.json";
                    var text = JSON.stringify(res.data);
                    downloadJson(filename, text);
                } else {
                    layer.msg("导出数据失败", {icon: 2, time: 1500});
                }
            })
        })
        ...
    }
    
    /**
     * 下载为json文件
     * @param filename
     * @param text
     */
    function downloadJson(filename, text) {
        var pom = document.createElement('a');
        pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
        pom.setAttribute('download', filename);
        if (document.createEvent) {
            var event = document.createEvent('MouseEvents');
            event.initEvent('click', true, true);
            pom.dispatchEvent(event);
        } else {
            pom.click();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
后端代码
  1. controller

    @Autowired
    ConfigDictService configDictService;
    
    /**
     * 向数据字典中导入图层字段
     *
     * @param file
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping("/importLayerField")
    ResponseData importLayerField(@RequestPart(name = "file") MultipartFile file, HttpServletRequest request) throws IOException {
        String parentId = request.getParameter("parentId");
        StringBuilder layerFieldInfoStr = null;
        try {
            if (file != null) {
                InputStream stream = file.getInputStream();
                InputStreamReader streamReader = new InputStreamReader(stream, StandardCharsets.UTF_8);
                BufferedReader reader = new BufferedReader(streamReader);
                String line;
                layerFieldInfoStr = new StringBuilder();
                while ((line = reader.readLine()) != null) {
                    layerFieldInfoStr.append(line);
                }
                reader.close();
                stream.close();
                boolean flag = configDictService.savelayerFieldInfo(layerFieldInfoStr.toString(), parentId);
                if (!flag) {
                    return fail("导入失败");
                }
            } else {
                return fail("上传的数据为空");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return successWithData(true);
    }
    
    /**
     * 将选中的图层字段导出,若未选中,则导出所有的图层字段
     *
     * @param selectedIdList
     * @param parentId
     * @return
     */
    @PostMapping("/exportLayerField")
    public ResponseData exportLayerField(@RequestBody List<String> selectedIdList,
                                         @RequestParam(name = "parentId") String parentId) {
        // 根据selectedIdList查询图层字段目录
        List<ConfigDict> layerFieldCatalogList = configDictService.selectByIdList(selectedIdList, parentId);
        JSONObject exportJson = new JSONObject();
        List<JSONObject> layerFieldCatalogJSONList = new ArrayList<>();
        // 遍历层字段目录,查询每个目录下的图层字段,构造JSON
        for (ConfigDict layerFieldCatalog : layerFieldCatalogList) {
            JSONObject layerFieldCatalogJSON = (JSONObject) JSONObject.toJSON(layerFieldCatalog);
            layerFieldCatalogJSON.remove("updateAt");
            layerFieldCatalogJSON.remove("createAt");
            layerFieldCatalogJSON.remove("operator");
            layerFieldCatalogJSON.remove("id");
            layerFieldCatalogJSON.remove("parentId");
            List<ConfigDict> layerFieldItemList = configDictService.findItemByParentId(layerFieldCatalog.getId());
            List<JSONObject> layerFieldItemJSONList = new ArrayList<>();
            for (ConfigDict layerFieldItem : layerFieldItemList) {
                JSONObject layerFieldItemJSON = (JSONObject) JSONObject.toJSON(layerFieldItem);
                layerFieldItemJSON.remove("updateAt");
                layerFieldItemJSON.remove("createAt");
                layerFieldItemJSON.remove("operator");
                layerFieldItemJSON.remove("id");
                layerFieldItemJSON.remove("parentId");
                layerFieldItemJSONList.add(layerFieldItemJSON);
            }
            layerFieldCatalogJSON.put("layerFieldList", layerFieldItemJSONList);
            layerFieldCatalogJSONList.add(layerFieldCatalogJSON);
        }
        exportJson.put("gt_layer_Field", layerFieldCatalogJSONList);
        return successWithData(exportJson);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
  2. service接口

    /**
     * 向数据字典中保存图层字段信息
     *
     * @param layerFieldInfoStr
     * @param parentId
     * @return
     */
    boolean savelayerFieldInfo(String layerFieldInfoStr, String parentId);
    
    /**
     * 根据selectedIdList查询图层字段目录,若selectedIdList为空,则查询所有的图层字段目录
     *
     * @param selectedIdList
     * @param parentId
     * @return
     */
    List<ConfigDict> selectByIdList(List<String> selectedIdList, String parentId);
    
    /**
     * 根据parentId获取所有item字典项
     *
     * @param parentId
     * @return
     */
    List<ConfigDict> findItemByParentId(String parentId);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
  3. service接口实现类

    @Autowired
    ConfigDictService configDictService;
    
    /**
     * 向数据字典中保存图层字段信息
     *
     * @param layerFieldInfoStr
     * @param parentId
     * @return
     */
    @Override
    public boolean savelayerFieldInfo(String layerFieldInfoStr, String parentId) {
        try {
            // 查询出当前所有的图层字段目录编码,若导入信息的编码已经存在,则不进行导入
            QueryWrapper<ConfigDict> queryWrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(parentId)) {
                queryWrapper.eq(ConfigDict.PARENT_ID, parentId);
            }
            queryWrapper.eq(ConfigDict.TYPE, CATALOG);
            List<ConfigDict> curLayerFieldList = baseMapper.selectList(queryWrapper);
            List<String> curLayerFieldCodeList = curLayerFieldList.stream().map(ConfigDict::getCode).collect(Collectors.toList());
            // 遍历导入的JSON,将需要插入的信息保存到数据库
            List<ConfigDict> insertLayerFieldItemList = new LinkedList<>();
            Map<String, List<Map>> layerFieldJSON = JSON.parseObject(layerFieldInfoStr, Map.class);
            List<Map> layerFieldCatalogMapList = layerFieldJSON.get("gt_layer_Field");
            if (ObjectUtil.isNotEmpty(layerFieldCatalogMapList)) {
                for (Map layerFieldCatalogMap : layerFieldCatalogMapList) {
                    List<ConfigDict> layerFieldItemList = JSON.parseArray(JSON.toJSONString(layerFieldCatalogMap.get("layerFieldList")), ConfigDict.class);
                    layerFieldCatalogMap.keySet().removeIf(key -> key == "layerFieldList");
                    ConfigDict layerFieldCatalog = JSON.parseObject(JSON.toJSONString(layerFieldCatalogMap), ConfigDict.class);
                    if (!curLayerFieldCodeList.contains(layerFieldCatalog.getCode())) {
                        layerFieldCatalog.setParentId(parentId);
                        layerFieldCatalog.setType(CATALOG);
                        ConfigDict insertLayerFieldCatalog = configDictService.saveAndUpdate(layerFieldCatalog);
                        if (ObjectUtil.isNotEmpty(layerFieldItemList)) {
                            for (ConfigDict layerFieldItem : layerFieldItemList) {
                                layerFieldItem.setParentId(insertLayerFieldCatalog.getId());
                                layerFieldItem.setType(ITEM);
                                insertLayerFieldItemList.add(layerFieldItem);
                            }
                        }
                    }
                }
            }
            configDictService.saveBatch(insertLayerFieldItemList);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    
    /**
     * 根据selectedIdList查询图层字段目录,若selectedIdList为空,则查询所有的图层字段目录
     *
     * @param selectedIdList
     * @param parentId
     * @return
     */
    @Override
    public List<ConfigDict> selectByIdList(List<String> selectedIdList, String parentId) {
        List<ConfigDict> selectedList = new LinkedList<>();
        QueryWrapper<ConfigDict> queryWrapper = new QueryWrapper<>();
        if (selectedIdList.size() == 0) {
            if (StringUtils.isNotBlank(parentId)) {
                queryWrapper.eq(ConfigDict.PARENT_ID, parentId);
            }
            queryWrapper.eq(ConfigDict.TYPE, CATALOG);
            selectedList = baseMapper.selectList(queryWrapper);
        } else {
            selectedList = baseMapper.selectBatchIds(selectedIdList);
        }
        return selectedList;
    }
    
    /**
     * 根据parentId获取所有item字典项
     *
     * @param parentId
     * @return
     */
    @Override
    public List<ConfigDict> findItemByParentId(String parentId) {
        QueryWrapper<ConfigDict> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(parentId)) {
            queryWrapper.eq(ConfigDict.PARENT_ID, parentId);
        }
        queryWrapper.eq(ConfigDict.TYPE, ITEM);
        return baseMapper.selectList(queryWrapper);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/羊村懒王/article/detail/158017
推荐阅读
相关标签
  

闽ICP备14008679号