Reputation: 3748
Background: When using Microsoft Word one can define fields which are then being replaced with some values.
For example adding the following and then activating the field function will then display the title of the document (defined in the properties).
Question: is there any way to add such fields when generating my Word document with Apache POI so that the end user sees the correct values (I will also provide the values for the fields). I looked through the methods defined on the Document object but did not see anything useful. Just writing this string in the document is not going to work (kind of obvious...)
Edit: The XML for some field looks like this (in this case the AUTHOR of the document)
<w:p w:rsidRDefault="00AB5E40" w:rsidR="009B15AD">
<w:fldSimple w:instr=" AUTHOR \* MERGEFORMAT ">
<w:r>
<w:rPr>
<w:noProof/>
</w:rPr>
<w:t>My Name</w:t>
</w:r>
</w:fldSimple>
</w:p>
Upvotes: 1
Views: 4637
Reputation: 3748
Answering my own question in case somebody has a similar problem. As Gagravarr pointed out, there is no high-level API for this but by looking at the XML structure I came up with this:
private static void addField(XWPFParagraph paragraph, String fieldName) {
CTSimpleField ctSimpleField = paragraph.getCTP().addNewFldSimple();
ctSimpleField.setInstr(fieldName + " \\* MERGEFORMAT ");
ctSimpleField.addNewR().addNewT().setStringValue("<<fieldName>>");
}
Calling this method with some paragraph you have at hand and a field name will render this field in your document (either with the correct value or with << fieldName >>)
Upvotes: 3