如何使用 poi 3.8 替换 java 中 docx 标头中的占位符 [英] How to replace placeholders in header of docx in java using poi 3.8

查看:65
本文介绍了如何使用 poi 3.8 替换 java 中 docx 标头中的占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要替换 docx 文件标题中的标记.我已经处理了段落和表格中的标记替换,但它没有选择标题数据.我使用 apache poi 3.8 并使用 eclipse ID 在 java 中编码.谢谢

I'm tying to replace tokens in the header of docx file.I have handled the token replacement in paragraphs and tables but its not picking the header data. Im using apache poi 3.8 and coding in java using eclipse ID. Thanx

推荐答案

此方法将替换整个文档中的表格、标题和段落中的所有选定文本.

This methods will replace all selected text, in tables, headers and paragraph, in the entire document.

public XWPFDocument replacePOI(XWPFDocument doc, String placeHolder, String replaceText){
    // REPLACE ALL HEADERS
    for (XWPFHeader header : doc.getHeaderList()) 
        replaceAllBodyElements(header.getBodyElements(), placeHolder, replaceText);
    // REPLACE BODY
    replaceAllBodyElements(doc.getBodyElements(), placeHolder, replaceText);
    return doc;
}

private void replaceAllBodyElements(List<IBodyElement> bodyElements, String placeHolder, String replaceText){
    for (IBodyElement bodyElement : bodyElements) {
        if (bodyElement.getElementType().compareTo(BodyElementType.PARAGRAPH) == 0)
            replaceParagraph((XWPFParagraph) bodyElement, placeHolder, replaceText);
        if (bodyElement.getElementType().compareTo(BodyElementType.TABLE) == 0)
            replaceTable((XWPFTable) bodyElement, placeHolder, replaceText);
    }
}

private void replaceTable(XWPFTable table, String placeHolder, String replaceText) {
    for (XWPFTableRow row : table.getRows()) {
        for (XWPFTableCell cell : row.getTableCells()) {
            for (IBodyElement bodyElement : cell.getBodyElements()) {
                if (bodyElement.getElementType().compareTo(BodyElementType.PARAGRAPH) == 0) {
                    replaceParagraph((XWPFParagraph) bodyElement, placeHolder, replaceText);
                }
                if (bodyElement.getElementType().compareTo(BodyElementType.TABLE) == 0) {
                    replaceTable((XWPFTable) bodyElement, placeHolder, replaceText);
                }
            }
        }
    }  
}

private void replaceParagraph(XWPFParagraph paragraph, String placeHolder, String replaceText) {
    for (XWPFRun r : paragraph.getRuns()) {
        String text = r.getText(r.getTextPosition());
        if (text != null && text.contains(placeHolder)) {
            text = text.replace(placeHolder, replaceText);
            r.setText(text, 0);
        }
    }
}

这篇关于如何使用 poi 3.8 替换 java 中 docx 标头中的占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆