当点位于占位符内时,无法在页眉/页脚中使用Apache POI替换文本

时间:2019-05-28 09:27:02

标签: java ms-word apache-poi

我使用templ4docx / Apache POI(2.0.3 / 3.17)。 您可以在此处设置如下所示的VariablePatten:

private static final String START_PATTERN = "#{";
private static final String END_PATTERN = "}";
...
targetDocx.setVariablePattern(new VariablePattern(START_PATTERN, END_PATTERN));

当我使用带点的占位符时,它在页眉/页脚内部不起作用。在带有圆点的主体中有效。而且图像也可以使用占位符和内部的点!

Example in Word-Template:
#{Person.Name} // works in Body NOT in Header/Footer!
#{Person.Name} // works in Body and Header/Footer!
#{Person} // works in Body and Header/Footer!
#{Image.Name} // works in Body and Header/Footer! Here i use ImageVariable instead of Textvariable.

我调试代码,看到用正确的Text调用了“ run.setText()”,但在最终文档中却没有。

@Override
public void insert(Insert insert, Variable variable) {
    if (!(insert instanceof TextInsert)) {
        return;
    }
    if (!(variable instanceof TextVariable)) {
        return;
    }

    TextInsert textInsert = (TextInsert) insert;
    TextVariable textVariable = (TextVariable) variable;
    for (XWPFRun run : textInsert.getParagraph().getRuns()) {
        String text = run.getText(0);
        if (StringUtils.contains(text, textInsert.getKey().getKey())) {
            text = StringUtils.replace(text, textVariable.getKey(), textVariable.getValue());
            if (text.contains("\n")) {
                String[] textLines = text.split("\n");
                run.setText(textLines[0], 0);
                for (int i = 1; i < textLines.length; i++) {
                    run.addBreak();
                    run.setText(textLines[i]);
                }
            } else {
                run.setText(text, 0);
            }
        }
    }
}

有什么想法为什么它不能与占位符“#{Person.Name}”一起用作页眉/页脚中的TextVariable?但是它可以与“#{PersonName}”和ImageVariable“#{Images.Logo1}”一起使用?

1 个答案:

答案 0 :(得分:0)

看起来Word有时会分隔占位符,所以您只能在运行中找到占位符的一部分。

在“ TextInsertStrategy”类中,我在运行循环中检查是否有拆分占位符,并对其进行相应处理。这样我就可以解决问题了。