guerda guerda - 1 year ago 142
Java Question

How can I create a simple docx file with Apache POI?

I'm searching for a simple example code or a complete tutorial how to create a

file with Apache POI and its underlying

I tried the following code (with a lot of help from the Content Assist, thanks Eclipse!) but the code does not work correctly.

String tmpPathname = aFilename + ".docx";
File tmpFile = new File(tmpPathname);

ZipPackage tmpPackage = (ZipPackage) OPCPackage.create(tmpPathname);
PackagePartName tmpFirstPartName = PackagingURIHelper.createPartName("/FirstPart");
PackagePart tmpFirstPart = tmpPackage.createPart(tmpFirstPartName, "ISO-8859-1");

XWPFDocument tmpDocument = new XWPFDocument(tmpPackage); //Exception
XWPFParagraph tmpParagraph = tmpDocument.createParagraph();
XWPFRun tmpRun = tmpParagraph.createRun();

The thrown exception is the following:

Exception in thread "main" java.lang.NullPointerException
at org.apache.poi.POIXMLDocument.load(
at org.apache.poi.xwpf.usermodel.XWPFDocument.<init>(
at DocGenerator.makeDocxWithPoi(
at DocGenerator.main(

Does anybody can help me with my (really simple) requirements?

Answer Source

Here is how you can create a simple docx file with POI :

XWPFDocument document = new XWPFDocument();
XWPFParagraph tmpParagraph = document.createParagraph();
XWPFRun tmpRun = tmpParagraph.createRun();
document.write(new FileOutputStream(new File("yourpathhere")));

PS the File must actually exist... and after this you should then go


to prevent a resource leak, deletion errors, etc.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download