Question
How can I create a simple docx file with Apache POI?
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import java.io.FileOutputStream;
import java.io.IOException;
Answer
Creating a DOCX file in Java can be seamlessly done using the Apache POI library, which provides support for a wide range of document formats, including Microsoft Word. In this guide, we'll walk you through the steps to create a simple DOCX file with text content using Apache POI.
public class CreateDocx {
public static void main(String[] args) {
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
run.setText("Hello World! This is a simple DOCX file created with Apache POI.");
try (FileOutputStream out = new FileOutputStream("SimpleDoc.docx")) {
document.write(out);
System.out.println("DOCX file created successfully!");
} catch (IOException e) {
e.printStackTrace();
} finally {
// Closing resources if needed
try {
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Causes
- Not having the Apache POI library added to your project.
- Incorrect usage of file output streams.
Solutions
- Make sure to include the Apache POI dependencies in your project.
- Always close the FileOutputStream in a finally block or use a try-with-resources statement.
Common Mistakes
Mistake: Forgetting to include Apache POI libraries in your project.
Solution: Ensure that Apache POI and its dependencies are included in your build configuration (e.g., Maven, Gradle).
Mistake: Not properly closing file streams, leading to resource leaks.
Solution: Use try-with-resources or ensure streams are closed in a finally block.
Helpers
- Apache POI tutorial
- create docx file java
- how to use Apache POI
- Java DOCX example