Apache POI is very useful for working on with the MS office files like Word, Excel etc. In the post we will how to create word doc file in java using POI.
Setup for Apache POI
1 2 3 4 5 |
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.15-beta2</version> </dependency> |
NOTE : For non maven users, you need to download the latest Apache POI jar from here and set it in your classpath along with some other jars.
1 2 3 4 |
poi-3.15-beta2.jar poi-ooxml-3.15-beta2.jar poi-ooxml-schemas-3.15-beta2.jar xmlbeans-2.6.0.jar |
Classes / Interfaces Used
XWPFDocument
org.apache.poi.xwpf.usermodel.XWPFDocument is used to create the MS Word Docs in the .docx formats.
The Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
package com.kscodes.test; import java.io.File; import java.io.FileOutputStream; import org.apache.poi.xwpf.usermodel.XWPFDocument; public class CreateDocUsingPOI { public static void main(String args[]) { XWPFDocument document = null; FileOutputStream fileOutputStream = null; try { document = new XWPFDocument(); File fileToBeCreated = new File("C:\\kscodes_temp\\FirstWordFile.docx"); fileOutputStream = new FileOutputStream(fileToBeCreated); document.write(fileOutputStream); System.out.println("Word Document Created Successfully !!!"); } catch (Exception e) { System.out.println("We had an error while creating the Word Doc"); } finally { try { if (document != null) { document.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } catch (Exception ex) { } } } } |
Output
When we run the above code we get the message on the console and a blank word document is created at the location we had specified.
1 |
Word Document Created Successfully !!! |
In few of the next posts we will see some of the other stuff we can do with Word documents using Apache POI.