Apache POI: How to create Paragraph in Word document? - BunksAllowed

BunksAllowed is an effort to facilitate Self Learning process through the provision of quality tutorials.

Community

Apache POI: How to create Paragraph in Word document?

Share This

Dependencies

First, download the dependency files as mentioned in the Introduction to Apache POI For Manipulation of MS Office Documents with Java tutorial. After downloading the libraries, you have to add them to JAVA_PATH. Alternatively, you can create an Eclipse project and add them to the project as a library. You are being suggested to add the libraries as an internal library instead of an external library.

If you are not familiar with library linking, follow these steps.

Create a directory, lib, in your project. Put the jars in the lib directory. Right-click on the project, select Properties, go to Java Build Path, click on Add Jars and browse the lib directory you have created. It's done!

Explanation of Source Code

    Create an instance of FileOutputStream for the Demo.docx file.
    Create an instance of XWPFDocument class for .docx file.
    Create an instance of XWPFParagraph class to create paragraphs.
    Prepare the content and finally write the content.

Try the following code.



package com.t4b.demo.poi; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; public class WordDocumentParagraphDemo { public static void main(String[] args) throws FileNotFoundException, IOException { XWPFDocument doc = new XWPFDocument(); try { OutputStream outputStream = new FileOutputStream("Demo.doc"); XWPFParagraph xwpfParagraph = doc.createParagraph(); XWPFRun xwpfRun = xwpfParagraph.createRun(); xwpfRun.setText("Dummy paragraph!"); doc.write(outputStream); doc.close(); } catch (Exception e) { e.printStackTrace(); } } }

Happy Exploring!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.