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.
1 2 3 4 5 6 7 8 9 10 11 |
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.16</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> |
2. Creating a word template
Now we need to create a template for the document.
That’s how it looks.
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.
1 |
XWPFDocument document = new XWPFDocument(OPCPackage.open("template.docx")); |
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.
1 2 3 4 5 6 7 8 9 10 |
XWPFDocument document = new XWPFDocument(OPCPackage.open("template.docx")); for (XWPFParagraph paragraph : document.getParagraphs()) { for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); text = text.replace("${name}", "John"); run.setText(text,0); System.out.println(text); } } document.write(new FileOutputStream("output.docx")); |
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:
Recomended books:
Hi, how can I replace an image in a word file using apache poi?
You have an image in a word document and you want to replace this image to another?
Hello,
I want to generate a Word Document with the method setonClickListener on a Button which is in my Main Activity but when I am Trying to do so it’s not working.
Can you tell me how to do it please ?