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);
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }

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

相关推荐
晴殇i几秒前
前端内容保护:如何有效防止用户复制页面内容?
前端·javascript·css
Coding小公仔4 分钟前
LeetCode 151. 反转字符串中的单词
开发语言·c++·算法
程序猿阿伟5 分钟前
《声音的变形记:Web Audio API的实时特效法则》
开发语言·前端·php
东阳马生架构8 分钟前
订单初版—2.生单链路中的技术问题说明文档
java
凌览9 分钟前
有了 25k Star 的MediaCrawler爬虫库加持,三分钟搞定某红书、某音等平台爬取!
前端·后端·python
万少11 分钟前
2-自然壁纸实战教程-AGC 新建项目
前端·harmonyos
满分观察网友z22 分钟前
别小看这个滑动条!从性能灾难到用户挚爱的 uni-app Slider 踩坑实录
前端
咖啡啡不加糖22 分钟前
暴力破解漏洞与命令执行漏洞
java·后端·web安全
满分观察网友z25 分钟前
别再裸写<textarea>了!一个“小”功能,我用上了它几乎所有API
前端
风象南25 分钟前
SpringBoot敏感配置项加密与解密实战
java·spring boot·后端