Apache POI Word - Document


Advertisements

Here the term 'document' refers to a MS-Word file. After completion of this chapter, you will be able to create new documents and open existing documents using your Java program.

Create Blank Document

The following simple program is used to create a blank MS-Word document −

import java.io.File;
import java.io.FileOutputStream;
import org.apache.poi.xwpf.usermodel.XWPFDocument;

public class CreateDocument {

   public static void main(String[] args)throws Exception  {
   
      //Blank Document
      XWPFDocument document = new XWPFDocument(); 
		
      //Write the Document in file system
      FileOutputStream out = new FileOutputStream( new File("createdocument.docx"));
      document.write(out);
      out.close();
      System.out.println("createdocument.docx written successully");
   }
}

Save the above Java code as CreateDocument.java, and then compile and execute it from the command prompt as follows −

$javac  CreateDocument.java
$java CreateDocument

If your system environment is configured with the POI library, it will compile and execute to generate a blank Excel file named createdocument.docx in your current directory and display the following output in the command prompt −

createdocument.docx written successfully
Advertisements