Java查询数据放入word模板中并在前端导出下载

需求:查询数据放入word模板中并在前端导出下载

解决方法:在模板的位置定义参数如 {{name}} {{age}}等等,使用 poi 处理

伪代码:

java 复制代码
    @PostMapping("/practiceAppr")
    public AjaxResult practiceAppr(OutputStream outputStream, @RequestBody ExportToExcelParamDto paramDto) {

        //查询数据  ExportToWordByPracticeApprDto 为定义的模板中的参数
        ExportToWordByPracticeApprDto app= baseService.practiceApprExport(paramDto);
        
                try {
                    //获取模板文件
                    try (InputStream is = TrActivityGroupServiceImpl.class.getClassLoader().getResourceAsStream("word/导出模板A4.docx")
                    ) {
                        try (XWPFDocument doc = new XWPFDocument(is)
                        ) {
                            Map<String, Object> replaceMap = BeanUtil.beanToMap(app);
                            Map<String, Object> resultMap = new HashMap<>();
                            //word中的占位符格式是{{}}
                            replaceMap.forEach((placeholder, replacement) -> resultMap.put("{{" + placeholder + "}}", replacement));
                            //处理文件替换参数为实际值
                            replacePlaceholders(doc, resultMap);
                            doc.write(outputStream);
                            outputStream.close();
                            is.close();
                        }
                    }
                } catch (Exception e) {
                    logger.error("文件导出错误{}", e.getMessage());
                }
          
        return null;
    }



private void replacePlaceholders(XWPFDocument document, Map<String, Object> placeholders) throws IOException, InvalidFormatException {
        //处理普通word文字 不包含表格
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            List<XWPFRun> runs = paragraph.getRuns();
            for (XWPFRun run : runs) {
                String text = run.getText(0);
                if (text != null) {
                    for (Map.Entry<String, Object> entry : placeholders.entrySet()) {
                        if (text.contains(entry.getKey())) {
                            text = text.replace(entry.getKey(), entry.getValue() != null ? (String) entry.getValue() : "");
                            run.setText(text, 0);
                        }
                    }
                }
            }
        }

        // 处理替换表格中的占位符
        for (XWPFTable table : document.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph paragraph : cell.getParagraphs()) {
                        List<XWPFRun> runs = paragraph.getRuns();
                        for (XWPFRun run : runs) {
                            String text = run.getText(0);
                            if (text != null) {
                                for (Map.Entry<String, Object> entry : placeholders.entrySet()) {
                                    if (text.contains(entry.getKey())) {
                                        //获取、处理图片略
                                        ...
                                        ...
                                            int format = XWPFDocument.PICTURE_TYPE_PNG;
                                           //图片地址
                                            BufferedImage image = ImageIO.read(new URL(value));
                                            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                                            //suffix为图片的后缀 .png
                                            ImageIO.write(image, suffix, outputStream);
                                            byte[] imageBytes = outputStream.toByteArray();
                                            //后两个参数是宽高
                                            run.addPicture(new ByteArrayInputStream(imageBytes), format, fileName, Units.toEMU(80), Units.toEMU(40));
                                         //替换文字  图片和文字如果都展示
                                        text = text.replace(entry.getKey(), entry.getValue() != null ? (String) entry.getValue() : "");
                                        run.setText(text, 0);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

最后前端处理进行下载即可。

相关推荐
渣哥4 分钟前
Java ThreadPoolExecutor 动态调整核心线程数:方法与注意事项
java
Moonbit9 分钟前
MoonBit 再次走进清华:张宏波受邀参加「思源计划」与「程序设计训练课」
前端·后端·编程语言
RestCloud12 分钟前
一站式数据集成:iPaaS 如何让开发者和业务人员都满意?
前端·后端·架构
Miraitowa_cheems15 分钟前
LeetCode算法日记 - Day 38: 二叉树的锯齿形层序遍历、二叉树最大宽度
java·linux·运维·算法·leetcode·链表·职场和发展
wanzhong233321 分钟前
学习triton-第1课 向量加法
开发语言·python·高性能计算
li357423 分钟前
React 核心 Hook 与冷门技巧:useReducer、useEffect、useRef 及 is 属性全解析
前端·javascript·react.js
菜市口的跳脚长颌26 分钟前
Web3 基础
前端
快乐是Happy27 分钟前
分享一个非常实用的防止重复提交操作
前端·javascript
王蛋11127 分钟前
前端工作问题或知识记录
前端·npm·node.js
云枫晖29 分钟前
JS核心知识-执行上下文
前端·javascript