In the last post we saw how to Create Word Doc file in Java Using POI. Now in this post we will see how to add Paragraph to Word doc using POI.
Classes / Interfaces Used
XWPFDocument
org.apache.poi.xwpf.usermodel.XWPFDocument is used to create the MS Word Docs in the .docx formats.
XWPFParagraph
org.apache.poi.xwpf.usermodel.XWPFParagraph is used to create a paragraph in the word file.
XWPFRun
org.apache.poi.xwpf.usermodel.XWPFRun is used to add/change the text in a specified element/region.
The Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
package com.kscodes.test; import java.io.File; import java.io.FileOutputStream; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; public class CreateParaWordDocPOI { public static void main(String args[]) { XWPFDocument document = null; FileOutputStream fileOutputStream = null; try { document = new XWPFDocument(); File fileToBeCreated = new File("C:\\kscodes_temp\\POI_Paragraph_test.docx"); fileOutputStream = new FileOutputStream(fileToBeCreated); // create Paragraph XWPFParagraph paragraph = document.createParagraph(); XWPFRun run = paragraph.createRun(); run.setText("We created a word file using Apache POI. And now we are writing into it as a paragraph. " + "Next, we will add some cool stuff to this Word document."); document.write(fileOutputStream); System.out.println("Paragraph created and written in Word File Succefully !!!"); } catch (Exception e) { System.out.println("We had an error while creating the Word Doc"); } finally { try { if (document != null) { document.close(); } if (fileOutputStream != null) { fileOutputStream.close(); } } catch (Exception ex) { } } } } |
Output
When we run the above code we get the message on the console and a word document is created at the location we had specified.
1 |
Paragraph created and written in Word File Succefully !!! |
In the coming posts we will see some of the other fun stuff that we can do with Word documents using Apache POI.