How to generate word document with apache poi

Today we will continue the topic of generating office documents from the template. To generate a docx document, we use the apache poi library.

1. Dependencies

Create an empty maven project and connect the following maven dependencies.

2. Creating a word template

Now we need to create a template for the document.
That’s how it looks.

Docx template
Docx template

Instead of the $ {name} text, you can use any sequence, the main thing is that it does not overlap with the main text of the document when you replace it.

3. Implementation

First, let’s create an instance of the  XWPFDocument class.

Then we consistently go through all the paragraphs and regions of the text inside them.

We check whether there is text for the replacement that we are looking for, and if so, replace it. At the end, we save the document.

After running the project, the output.docx file will be created, in which the finished report will be created.
This is how it will look:

Generated docx report
Generated docx report

Related Post

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.