本文介绍了docx4j查找并替换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些占位符的docx文档.现在,我应该用其他内容替换它们并保存新的docx文档.我从 docx4j 并找到此方法:

I have docx document with some placeholders. Now I should replace them with other content and save new docx document. I started with docx4j and found this method:

public static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
    List<Object> result = new ArrayList<Object>();
    if (obj instanceof JAXBElement) obj = ((JAXBElement<?>) obj).getValue();

    if (obj.getClass().equals(toSearch))
        result.add(obj);
    else if (obj instanceof ContentAccessor) {
        List<?> children = ((ContentAccessor) obj).getContent();
        for (Object child : children) {
            result.addAll(getAllElementFromObject(child, toSearch));
        }
    }
    return result;
}

public static void findAndReplace(WordprocessingMLPackage doc, String toFind, String replacer){
    List<Object> paragraphs = getAllElementFromObject(doc.getMainDocumentPart(), P.class);
    for(Object par : paragraphs){
        P p = (P) par;
        List<Object> texts = getAllElementFromObject(p, Text.class);
        for(Object text : texts){
            Text t = (Text)text;
            if(t.getValue().contains(toFind)){
                t.setValue(t.getValue().replace(toFind, replacer));
            }
        }
    }
}

但这很少起作用,因为通常占位符会分割成多个文本.

But that only work rarely because usually the placeholders splits across multiple texts runs.

我尝试了 UnmarshallFromTemplate ,但它也很少起作用.

I tried UnmarshallFromTemplate but it work rarely too.

该问题如何解决?

推荐答案

您可以使用 VariableReplace 来实现,而在其他答案时可能还不存在.这本身并不会执行查找/替换,但可以在占位符上使用,例如 $ {myField}

You can use VariableReplace to achieve this which may not have existed at the time of the other answers.This does not do a find/replace per se but works on placeholders eg ${myField}

java.util.HashMap mappings = new java.util.HashMap();
VariablePrepare.prepare(wordMLPackage);//see notes
mappings.put("myField", "foo");
wordMLPackage.getMainDocumentPart().variableReplace(mappings);

请注意,您不会传递 $ {myField} 作为字段名称;而不是传递未转义的字段名称 myField -这是相当不灵活的,因为从目前的角度来看,您的占位符必须采用 $ {xyz} 格式,而如果您可以传递任何内容那么您可以将其用于任何查找/替换.docx4j.NET中的C#人员也可以使用此功能

Note that you do not pass ${myField} as the field name; rather pass the unescaped field name myField - This is rather inflexible in that as it currently stands your placeholders must be of the format ${xyz} whereas if you could pass in anything then you could use it for any find/replace. The ability to use this also exists for C# people in docx4j.NET

请参见此处有关 VariableReplace 此处表示 VariablePrepare

这篇关于docx4j查找并替换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-28 11:48