Ofttimes, we need to automate our processes and manipulate the documents programmatically. We need to create documents in bulk, read, process, and save the resultant documents. We need to work with a bunch of different file formats simultaneously. Luckily, for Java developers, we have an open-source API to work with Word, Spreadsheet, Presentation, Email, and Diagram file-formats – Apache POI. This cross-platform API is designed to work with Java Virtual Machine (JVM) based languages.
How to Install
Installing Apache POI is effortless. All you need to do is add the dependency in your maven based project. You can add the following dependency in your pom.xml and get started with Apache POI.
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.0</version>
</dependency>
Create a Word Document
Using Apache POI you can create a word document using XWPFDocument and insert a paragraph in it using the XWPFParagraph class. The following code snippet shows how to create a Word document using the API.
// initialize a blank document
XWPFDocument document = new XWPFDocument();
// create a new file
FileOutputStream out = new FileOutputStream(new File("createdocument.docx"));
// create a new paragraph paragraph
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("File Format Developer Guide - " +
"Learn about computer files that you come across in " +
"your daily work at: www.fileformat.com ");
document.write(out);
out.close();
System.out.println("Document created successfully")
The following is the resultant output document: