how to create a new word from template with docx4j

后端 未结 1 1543
无人共我
无人共我 2021-01-03 08:29

I have the following scenario, and need some advice:

The user will input a word document as a template, and provide some parameters in runtime so i can query my data

1条回答
  •  一生所求
    2021-01-03 08:59

    docx4j includes VariablePrepare, which can tidy up your input docx so that your keys are not split across separate runs.

    But, you would still be better off switching to content control data binding, particularly if you have repeated data (think for example of line items in an invoice). Disclosure: I champion this approach in docx4j.

    To adopt the content control data binding approach:

    1. dream up an XML format which makes sense for your data, and write some code to convert the results of your database query into that format.

    2. modify your template, so that the content controls are bound to elements in your XML document. ordinarily you'd use an authoring add-in for Word to help with this. (The technology Microsoft uses for binding is XPath, so how you bind depends on your XML structure, but, yes, you'd typically bind to the element name or ID).

    3. now you have your XML file and a suitable intput docx, ContentControlsMergeXML contains the code you need to create an instance document at run time. There's also a version of this for a servlet environment at https://github.com/plutext/OpenDoPE-WAR

    As an alternative to 1 & 2, there is also org.docx4j.model.datastorage.migration.FromVariableReplacement in current nightlies, which can convert your existing "${" document. Only to a standardised target XML format though.

    If you have further questions, there is a forum devoted to this topic at http://www.docx4java.org/forums/data-binding-java-f16/

    0 讨论(0)
提交回复
热议问题