docx4j does not replace variables

2019-01-26 07:32发布

问题:

I just followed approach No 2 in the VariableReplace example from docx4j 2.8.1 and everything it does, is to remove the variable markers ${}.

The steps I did:

  • Opened Word 2013, typed ${variable} as text only
  • Saved it to somewhere
  • read it in my Java program and build my HashMap with .put("variable", "TEST");
  • other code is copied and pasted from the example above.
  • Saved the document

I'd expect 'TEST' solely, and get just 'variable' without the markers in the output document.

回答1:

No doubt Word is splitting your "variable" across runs, with grammar or spelling flags.

Fix it up with VariablePrepare

Put this line in after you instantiate the WordprocessingMLPackage:

VariablePrepare.prepare(wordMLPackage);

Then you can use your mappings to replace the variables.



回答2:

I realize this is an old post, but for others that stumble onto this, another reason you can get this result is if you have incorrect "keys" in your HashMap. So in my case, I was using my old xml format as the key like

.put("<variable/>","TEST");

when I should have been using:

.put("variable","TEST");

The document itself was using tags like

${variable}

The VariableReplace code will remove the ${} formatting whether a match is found or not. So if it is not finding a match, then the keys might not match the ones in the document for some reason, and this might not strictly be related to VariablePrepare. But this was a very helpful post for me since the VariablePrepare, VariableReplace solution is now working for my purposes.

Also, I am not sure that even VariablePrepare can handle the case where you change the font, highlighting or other formatting in the middle of your tag in the document. In such cases, it will not be able to merge the tag into a single run, and so tag recognition will likely fail.



标签: docx4j