java替换word里面的占位符(包括标题、文本、表格、图片)

一、首先要有一个word文档

把需要的后台替换的地方改成占位符,然后放到指定的位置我的是放在了项目里面的某个路径下,

下面是word里面修改占位符的样子,图片也可以这样

二、项目导入对应的依赖或者下载对应的jar包
三、代码如下
//模板word的路径位置
String inputFile="input.docx"

//给刚刚文档里面的占位符号赋值
Map<String, String> params = new HashMap<>();
     params.put("${name}", 2024);
     params.put("${month}", 8);

//如果有图片占位符
 Map<String, String> imageMap = new HashMap<>();
imageMap.put("{firstImage}", "E:\\图片\\147f5ae9e26ce1d393ffb02886ce201.png");
XWPFDocument doc = new XWPFDocument(new FileInputStream(inputFile));
//替换后设置在浏览器导出
replaceImages(doc, imageMap);
replaceInParagraphs(doc, params);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=\"" + "output.docx" + "\"");
OutputStream os = response.getOutputStream();
doc.write(os);
os.close();
doc.close();



 private static void replaceInParagraphs(XWPFDocument doc, Map<String, String> params) {
        // 替换文档中的所有段落
        replaceInParagraphs(doc.getParagraphs(), params);
        // 替换表格中的内容(如果有表格)
        replaceInTables(doc.getTables(), params);
        // 替换页眉中的内容(如果有页眉)
        replaceInHeaders(doc.getHeaderList(), params);
        // 替换页脚中的内容(如果有页脚)
        replaceInFooters(doc.getFooterList(), params);
    }
    private static void replaceInParagraphs(List<XWPFParagraph> paragraphs, Map<String, String> replacements) {
        for (XWPFParagraph paragraph : paragraphs) {
            replaceText(paragraph, replacements);
        }
    }

    private static void replaceInTables(List<XWPFTable> tables, Map<String, String> replacements) {
        for (XWPFTable table : tables) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    replaceInParagraphs(cell.getParagraphs(), replacements);
                }
            }
        }
    }

    private static void replaceInHeaders(List<XWPFHeader> headers, Map<String, String> replacements) {
        for (XWPFHeader header : headers) {
            replaceInParagraphs(header.getParagraphs(), replacements);
        }
    }

    private static void replaceInFooters(List<XWPFFooter> footers, Map<String, String> replacements) {
        for (XWPFFooter footer : footers) {
            replaceInParagraphs(footer.getParagraphs(), replacements);
        }
    }

    private static void replaceText(XWPFParagraph paragraph, Map<String, String> replacements) {
        StringBuilder fullText = new StringBuilder();
        List<XWPFRun> runs = paragraph.getRuns();

        if (runs != null) {
            for (XWPFRun run : runs) {
                String text = run.getText(0);
                if (text != null) {
                    fullText.append(text);
                }
            }

            // 替换文本中的占位符
            String replacedText = fullText.toString();
            for (Map.Entry<String, String> entry : replacements.entrySet()) {
                replacedText = replacedText.replace(entry.getKey(), entry.getValue());
            }

            // 设置替换后的文本
            for (XWPFRun run : runs) {
                run.setText("", 0); // 清空原有文本
            }
            if (runs.size() > 0) {
                runs.get(0).setText(replacedText, 0);
            }
        }
    }
    public static void replaceImages(XWPFDocument document, Map<String, String> imageMap) throws IOException {
        for (XWPFParagraph paragraph : document.getParagraphs()) {
            for (XWPFRun run : paragraph.getRuns()) {
                String text = run.getText(0);
                if (text != null) {
                    for (Map.Entry<String, String> entry : imageMap.entrySet()) {
                        String placeholder = entry.getKey();
                        String imagePath = entry.getValue();

                        if (text.contains(placeholder)) {
                            // Replace placeholder text with empty string
                            run.setText(text.replace(placeholder, ""), 0);

                            // Load and add image
                            byte[] imageBytes = java.nio.file.Files.readAllBytes(java.nio.file.Paths.get(imagePath));
                            try {
                                String pictureIndex = document.addPictureData(imageBytes, 5);
//下面参数5是图片类型,这里是png对应的数字,如果是其它的可以自行百度,200设置的是图片高度,400是图片宽度
                                run.addPicture(new ByteArrayInputStream(imageBytes), 5, "image.png", Units.toEMU(400), Units.toEMU(200));
                            } catch (InvalidFormatException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }
                }
            }
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值