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

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

相关推荐
喵手6 分钟前
调试技巧:从 IDE 调试到生产环境定位问题,提升调试效率的全方位指南
java·ide·调试
AI_56786 分钟前
脑科学支持的Python学习法:每天2小时碎片化训练,用‘神经可塑性’打败拖延症“
开发语言·python·学习
用户9873824581018 分钟前
5. view component
前端
技术小丁10 分钟前
零依赖!教你用原生 JS 把 JSON 数组秒变 CSV 文件
前端·javascript
Crystal32820 分钟前
原生 Vue + UniApp 的小程序或 App 项目里如何判断用户是否为首次下载应用
前端·vue.js
前端世界22 分钟前
当网络里混入“假网关”:用 Scapy 写一个 DHCP 欺骗检测器(附完整代码与讲解)
开发语言·网络·php
千里镜宵烛22 分钟前
Lua-编译,执行和错误
开发语言·lua
赵谨言34 分钟前
基于python二手车价值评估系统的设计与实现
大数据·开发语言·经验分享·python
喜欢读源码的小白38 分钟前
Spring Boot+MyBatis实现无限层级组织架构设计|邻接表vs闭包表性能对比|树形结构数据存储方案
java·数据库·组织结构·树级层级·无线层级
时间的情敌38 分钟前
基于 Vue3 及TypeScript 项目后的总结
前端·vue.js·typescript