Last Updated:

Create a Word document in docx format using Apache POI

In this article we will continue our acquaintance with the Java library Apache POI, namely, learn how to create documents of the MS Word package in the modern format..docx

If you are not familiar with the Apache POI library, read this article (a brief description and configuration of the library in a Java project). With this library, we already created an Excel file, edited it and just read the data from the xls file. Today is the time to practice on Word documents.

Today we will create a new docx file with headers and footers and some content. Let's get acquainted with a small theory and then proceed to the example of creating such a file.

To work with the modern MS Word document format, we will need the Apache POI library version 3.11 with the artifact . Please note that the template files of the MS Office package are constantly updated and improved, and the Apache POI itself is reworked, so the operability of the code provided in the article in new versions is not guaranteed.poi-ooxml

Attach the following dependency to your maven project:

Create a Word document (.docx) using Apache POI. Theory

In the description, we indicated that we will create a document with headers and footers, so let's get acquainted with special classes that will allow you to do this.

Apache POI also provides classes for working with headers and footers. Each of these classes has creation methods and . To work with the contents of a document, there are special classes and .XWPFHeaderFooterPolicyXWPFHeaderFooterPolicycreateHeader()createFooter()XWPFParagraphXWPFRun API

The progress of creating a docx document will be as follows:

  1. Withthe create object — to create a model of the docx document itself.XWPFDocument
  2. Create an instance of the XWPFHeaderFooterPolicy class to access headers and footers.
  3. Создаем экземпляры CTP for header and footer
  4. Create wrapper classes for each header and footer and body of the Word document.XWPFParagraph
  5. Install the resulting shells in the model and save the model to a file with the extension docx.XWPFDocument

 

Create a Word document in docx format using Apache POI. Example

And now let's implement our algorithm in code:

Note that the color of the text is set in the hexadecimal representation of RGB, that is, HEX, but without the # sign.

Let's run the example and look at the contents of the Apache POI Word Test document.docx on the F drive.

The footer is there, but just didn't fit in the screenshot.

Here's just an example of creating a Word document in docx format using the Apache POI library. Sign up for updates.