Java Program to Write a Paragraph in a Word Document
Java provides us various packages in-built into the environment, which facilitate the ease of reading, writing, and modifying the documents. The package org.apache.poi.xwpf.usermodel provides us the various features of formatting and appending the content in word documents. There are various classes available in this package like XWPFDocument to create a new word document and XWPFParagraph to create and write new paragraphs into the corresponding created document. File class can be used to create a file at the specified path-name and FileOutputStream to create a file stream connection.
Approaches: The following procedure is followed to add a paragraph in the document :
1. XWPFDocument: A Java class to create and work with .docx files. Each time a blank .docx document is created. An object of this class is created, to begin with, the process, using new XWPFDocument() in Java. A file output stream is also parallel created to create and append contents of the document to a file at the local system. A stream connection is established by using FileOutputStream class.
2. XWPFParagraph: A Java class to create paragraphs corresponding to the XWPFDocument created. Multiple paragraphs can be created in a single document, each of which is instantiated using the specified document. The following method is invoked using the created object of the XWPFDocument in Java.
Return type: An object of the class XWPF Paragraph.
XWPFRun is a Java class to add a run to each of the paragraphs created in the document. XWPFRun simulates the addition of content to the paragraph using the createRun() method. The following method is invoked on the paragraph created in Java :
Return type: An object of the class XWPF Run.
The setText() method is invoked over this created run object to add content in Java :
Arguments: The content in string form is accepted as an argument.
Return type: Doesn’t return anything.
Note: The content specified in the document is then written to the file stream connection using the stream connection object and appended by invoking write() method over the XWPFDocument object. And, then the connection is closed successively.
Implementation: Java Programming to Write a paragraph in a Word Document
Output: The program produces the following file in the local directory: