How to Create a Word Document in Java

By Jim Campbell

Create Word documents with Java.
i document image by AGphotographer from

The Word format is a commonly used standard for desktop word-processing documents. The Java language provides developers with a language to create desktop and web applications. You can use Java to generate Word documents for your users. Users can open the newly created documents on their desktops, send them to others using email or simply keep them on their hard drives. Creating Word documents only takes a few lines of code.

Step 1

Create the document object. The document object contains all the methods and properties used to create the Word document. The following code creates the object:

Document doc = new Document();

Step 2

Create the Word file on the hard drive and open it. The file is opened to allow the Java application to write to it. The following code shows you how to create the file:

RtfWriter2.getInstance(doc, new FileOutputStream(\"file.doc\")) GO;

Step 3

Create some text. You can fill the document with several lines of text. In this example, only one paragraph is created. The following code creates a paragraph:

Paragraph para = new Paragraph() para.add(\"Just another paragraph of text\");

Step 4

Add the text to the Word document. The following code adds the paragraph to the file:


Step 5

Close the file. You close the file to release it from memory, which frees up resources on the computer. The following code closes the file: