In this chapter you will learn how to create a Paragraph and how to add it to a document using Java. Paragraph is a part of a page in a Word file.

After completing this chapter, you will be able to create a Paragraph and perform read operations on it.

Create a Paragraph

First of all, let us create a Paragraph using the referenced classes discussed in the earlier chapters. By following the previous chapter, create a Document first, and then we can create a Paragraph.

The following code snippet is used to create a spreadsheet −

  1. //Create Blank document
  2. XWPFDocument document = new XWPFDocument();
  3.  
  4. //Create a blank spreadsheet
  5. XWPFParagraph paragraph = document.createParagraph();
## Run on Paragraph

You can enter the text or any object element, using Run. Using Paragraph instance you can create run.

The following code snippet is used to create a Run.

  1. XWPFRun run = paragraph.createRun();
## Write into a Paragraph

Let us try entering some text into a document. Consider the below text data −

  1. At tutorialspoint.com, we strive hard to provide quality tutorials for self-learning
  2. purpose in the domains of Academics, Information Technology, Management and Computer
  3. Programming Languages.

The following code is used to write the above data into a paragraph.

  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  4. import org.apache.poi.xwpf.usermodel.XWPFParagraph;
  5. import org.apache.poi.xwpf.usermodel.XWPFRun;
  6.  
  7. public class CreateParagraph {
  8.  
  9. public static void main(String[] args)throws Exception {
  10.  
  11. //Blank Document
  12. XWPFDocument document = new XWPFDocument();
  13.  
  14. //Write the Document in file system
  15. FileOutputStream out = new FileOutputStream(new File(“createparagraph.docx”));
  16.  
  17. //create Paragraph
  18. XWPFParagraph paragraph = document.createParagraph();
  19. XWPFRun run = paragraph.createRun();
  20. run.setText(“At tutorialspoint.com, we strive hard to +
  21. provide quality tutorials for self-learning +
  22. purpose in the domains of Academics, Information +
  23. Technology, Management and Computer Programming
  24. Languages.”);
  25.  
  26. document.write(out);
  27. out.close();
  28. System.out.println(“createparagraph.docx written successfully”);
  29. }
  30. }

Save the above Java code as CreateParagraph.java, and then compile and run it from the command prompt as follows −

  1. $javac CreateParagraph.java
  2. $java CreateParagraph

It will compile and execute to generate a Word file named createparagraph.docx in your current directory and you will get the following output in the command prompt −

  1. createparagraph.docx written successfully

The createparagraph.docx file looks as follows.

createparagraph.jpg