docx4j find and replace

后端 未结 4 1889
梦如初夏
梦如初夏 2021-01-06 17:42

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:

         


        
4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-06 17:56

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

    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

    See here for more info on VariableReplace or here for VariablePrepare

提交回复
热议问题