用文本替换内容控件

时间:2018-04-30 12:47:25

标签: java docx4j

2 个答案:

答案 0 :(得分:0)

我自己在docx4j中处理内容控件。如果您只想查看docx文件的xml,可以使用.zip替换.docx文件扩展名,这实质上就是它。然后进入zip文件,你会发现底层的xml。我相信有些应用程序可以让你编辑和保存docx xml,但还没有看到那么多。

如果要在单词模板中插入内容控件,首先需要打开开发人员选项卡。见https://msdn.microsoft.com/en-us/library/bb608625.aspx。这将在开发人员选项卡下添加控件部分。见:https://gregmaxey.com/word_tip_pages/content_controls.html

我还没有找到一个很好的例子,只用XmlUtils.unmarshallFromTemplate(xmlString,mappings)来控制实际的变量替换,这似乎有很多夸克。如果您正在解决这个问题,请发布。

答案 1 :(得分:0)

    private static void replaceTextValue(WordprocessingMLPackage template, String name, String placeholder)
        throws Exception {

    List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), SdtBlock.class);
    // System.out.println(template.getMainDocumentPart().getXML());
    for (Object text : texts) {
        SdtBlock textElement = (SdtBlock) text;
        List<Object> cList = textElement.getSdtContent().getContent();
        ClassFinder finder = new ClassFinder(Text.class);
        new TraversalUtil(cList, finder);
        for (Object o : finder.results) {
            Object o2 = XmlUtils.unwrap(o);
            if (o2 instanceof org.docx4j.wml.Text) {
                String CTagVal = ((org.docx4j.wml.Text) o2).getValue();

                if (CTagVal.equalsIgnoreCase(placeholder)) {
                    org.docx4j.wml.Text txt = (org.docx4j.wml.Text) o2;
                    txt.setValue(name);
                }
            } else {
                System.out.println(XmlUtils.marshaltoString(o, true, true));
            }
        }
    }
}

此方法替换控件中的文本

相关问题