Apache POI: How to Create a Word File in Java
The Apache POI API provides the ability to create a new Word document and open the existing file using Java. This tutorial explains in the simplest way how to download and use this API to create a Word.
This tutorial is an introductory tutorial and just shows how to download and create an empty Word file. I advise you to read this tutorial: writing in a Word file in java which explains how to add text.
The XWPFDocument
This class in the org.apache.poi.xwpf.usermodel package is used to create a new MS-Word document with the .docx extension. Download the Apache poi API. Import the following files into your project's classpath:- poi.jar
- poi-ooxml.jar
- poi-ooxml-schemas.jar
- ooxml-lib\dom4j.jar
- ooxml-lib\xmlbeans.jar
- poi-scratchpad.jar
import java.io.File;Run:
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class CreateDocument
{
public static void main(String[] args)throws Exception
{
//Word document blank
XWPFDocument document= new XWPFDocument();
//create the document in the specific path by giving it a name
File nv_fichier = new File("nouveauFichier.docx");
FileOutputStream out = new FileOutputStream(nv_fichier);
document.write(out);
out.close();
System.out.println("The document "+ nv_fichier +" has been successfully created");
}
}
The createdocument.docx document was created successfullyRun time indicates that the Word file was created successfully. Java compiles and runs this program to generate an empty Word file named nouveauFichier.docx in the path you specified. In our case, this is the current directory of our project.
This tutorial is an introductory tutorial and just shows how to download and create an empty Word file. I advise you to read this tutorial: writing in a Word file in java which explains how to add text.