首页 > 解决方案 > 用文本替换内容控件

问题描述

我需要使用 docx4j 用 word 文档中的文本替换内容控件

我参考了这个链接,我无法理解如何从 .docx 文件中获取 .xml 文件 有谁知道我在哪里可以找到这方面的代码示例?

标签: javadocx4j

解决方案


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

此方法替换控件内的文本


推荐阅读