How to Create a Word Document in Javaby Jim Campbell
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.
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();
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 doc.open();
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\");
Add the text to the Word document. The following code adds the paragraph to the file: doc.add(para);
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: doc.close();
- document image by AGphotographer from Fotolia.com