How To Generate Word Documents In Java

Word documents have been widely used to create reports, quotations, invoices, etc. Generating Word documents automatically could save us lots of time and energy. This article will show you how to create a Word document on Java applications.
 

Add Spire.Doc.jar as a dependency

 
First of all, download Free Spire.Doc for Java 2.7.3. Unzip it, and you’ll get the jar file from the ‘lib’ folder. Then, create a Java application in your IDE. Import the jar file in your project as a dependency.
 
In the following sections, I will introduce how to insert different elements such as text, paragraphs, tables, lists and images, to a Word document.
 

Create a Word document

 
Usually, a large part of the content in a Word document is text. Firstly, we need to create a new instance of Document. And then add a section by Document.addSection() method and add a paragraph to the section by Section.addParagraph() method. After that, add text strings in paragraph by Paragraph.appendText(string text) method. We could also set the styles and format by ParagraphStyle. Finally, invoke document.saveToFile() method to save the document.
  1. //Create a Document instance  
  2. Document document = new Document();  
  3.   
  4. //Add a section  
  5. Section section = document.addSection();  
  6.   
  7. //Add two paragraphs to the section  
  8. Paragraph para1 = section.addParagraph();  
  9. para1.appendText("How to create Word document in Java");  
  10.   
  11. Paragraph para2 = section.addParagraph();  
  12. para2.appendText("This article demonstrate how to create Word document with text, images, lists and tables.");  
  13.   
  14. //Set title style for paragraph 1  
  15. ParagraphStyle style1 = new ParagraphStyle(document);  
  16. style1.setName("titleStyle");  
  17. style1.getCharacterFormat().setBold(true);  
  18. style1.getCharacterFormat().setTextColor(Color.BLUE);  
  19. style1.getCharacterFormat().setFontName("Arial");  
  20. style1.getCharacterFormat().setFontSize(12f);  
  21. document.getStyles().add(style1);  
  22. para1.applyStyle("titleStyle");  
  23.   
  24. //Set style for paragraph 2  
  25. ParagraphStyle style2 = new ParagraphStyle(document);  
  26. style2.setName("paraStyle");  
  27. style2.getCharacterFormat().setFontName("Arial");  
  28. style2.getCharacterFormat().setFontSize(11f);  
  29. document.getStyles().add(style2);  
  30. para2.applyStyle("paraStyle");  
  31.   
  32.   
  33. //Horizontally align paragraph 1 to center  
  34. para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);  
  35.   
  36. //Set first-line indent for paragraph 2  
  37. para2.getFormat().setFirstLineIndent(12f);  
  38.   
  39. //Set spaces after paragraph 1 and 2  
  40. para1.getFormat().setAfterSpacing(15f);  
  41. para2.getFormat().setAfterSpacing(10f);  
  42.   
  43. //Save the document  
  44. document.saveToFile("Output.docx", FileFormat.Docx);  
Output
 
How To Generate Word Documents In Java
 

Create a table in Word

 
Table sets text into rows and columns, which makes the text easy to edit and check. Spire.Doc for Java offers a method section.addTable() to add tables to the Word document. We can use Table.resetCells(int rowsNum, int columnsNum) method to set row and column numbers.
  1. //Create a Document instance  
  2. Document document = new Document();  
  3.   
  4. //Add a section  
  5. Section section = document.addSection();  
  6.   
  7. //Define data to create table  
  8. String[] header = {"Name""Gender"};  
  9. String[][] data =  
  10.         {  
  11.                 new String[]{"Winny""Female"},  
  12.                 new String[]{"Lois""Female"},  
  13.                 new String[]{"Jois""Female"},  
  14.                 new String[]{"Moon""Male"},  
  15.                 new String[]{"Vinit""Female"},  
  16.         };  
  17.   
  18. //Add a table  
  19. Table table = section.addTable();  
  20. table.resetCells(data.length + 1, header.length);  
  21. table.applyStyle(DefaultTableStyle.Colorful_List);  
  22. table.getTableFormat().getBorders().setBorderType(BorderStyle.Single);  
  23.   
  24. //Set the first row as table header and add data  
  25. TableRow row = table.getRows().get(0);  
  26. row.isHeader(true);  
  27. row.setHeight(20);  
  28. row.setHeightType(TableRowHeightType.Exactly);  
  29. row.getRowFormat().setBackColor(Color.gray);  
  30. for (int i = 0; i < header.length; i++) {  
  31.     row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);  
  32.     Paragraph p = row.getCells().get(i).addParagraph();  
  33.     p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);  
  34.     TextRange range1 = p.appendText(header[i]);  
  35.     range1.getCharacterFormat().setFontName("Arial");  
  36.     range1.getCharacterFormat().setFontSize(12f);  
  37.     range1.getCharacterFormat().setBold(true);  
  38. }  
  39.   
  40. //Add data to the rest of rows  
  41. for (int r = 0; r < data.length; r++) {  
  42.     TableRow dataRow = table.getRows().get(r + 1);  
  43.     dataRow.setHeight(25);  
  44.     dataRow.setHeightType(TableRowHeightType.Exactly);  
  45.     dataRow.getRowFormat().setBackColor(Color.white);  
  46.     for (int c = 0; c < data[r].length; c++) {  
  47.         dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);  
  48.         TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);  
  49.         range2.getCharacterFormat().setFontName("Arial");  
  50.         range2.getCharacterFormat().setFontSize(10f);  
  51.     }  
  52. }  
  53.   
  54. //Set background color for cells  
  55. for (int j = 1; j < table.getRows().getCount(); j++) {  
  56.     if (j % 2 == 0) {  
  57.         TableRow row2 = table.getRows().get(j);  
  58.         for (int f = 0; f < row2.getCells().getCount(); f++) {  
  59.             row2.getCells().get(f).getCellFormat().setBackColor(new Color(173216230));  
  60.         }  
  61.     }  
  62. }  
  63.   
  64. //Save the document  
  65. document.saveToFile("CreateTable.docx", FileFormat.Docx_2013);  
Output
 
How To Generate Word Documents In Java
 

Create lists in Word

 
There are two kinds of lists in Word: bulleted lists and numbered lists. Spire.Doc for Java offers Paragraph.getListFormat().applyBulletStyle() method and Paragraph.getListFormat().applyNumberedStyle() method to add the bulleted list and numbered list to the Word document.
  1. //load the Word document  
  2. Document document = new Document();  
  3. //add a section  
  4. Section section = document.addSection();  
  5. //add 8 paragraphs  
  6. Paragraph paragraph1 = section.addParagraph();  
  7. paragraph1.appendText("Bulleted List");  
  8. paragraph1.applyStyle(BuiltinStyle.Heading_1);  
  9. Paragraph paragraph2 = section.addParagraph();  
  10. paragraph2.appendText("Chapter 1");  
  11. Paragraph paragraph3 = section.addParagraph();  
  12. paragraph3.appendText("Chapter 2");  
  13. Paragraph paragraph4 = section.addParagraph();  
  14. paragraph4.appendText("Chapter 3");  
  15. Paragraph paragraph5 = section.addParagraph();  
  16. paragraph5.appendText("Numbered List");  
  17. paragraph5.applyStyle(BuiltinStyle.Heading_1);  
  18. Paragraph paragraph6 = section.addParagraph();  
  19. paragraph6.appendText("Chapter 1");  
  20. Paragraph paragraph7 = section.addParagraph();  
  21. paragraph7.appendText("Chapter 2");  
  22. Paragraph paragraph8 = section.addParagraph();  
  23. paragraph8.appendText("Chapter 3");  
  24. //create bulleted list for the 2-4 paragraphs  
  25. for(int i = 1; i < 4; i++){  
  26.     Paragraph para = section.getParagraphs().get(i);  
  27.     para.getListFormat().applyBulletStyle();  
  28.     para.getListFormat().getCurrentListLevel().setNumberPosition(-10);  
  29. }  
  30. //create numbered list for the 6-8 paragraphs  
  31. for(int i = 5; i < 8; i++){  
  32.     Paragraph para = section.getParagraphs().get(i);  
  33.     para.getListFormat().applyNumberedStyle();  
  34.     para.getListFormat().getCurrentListLevel().setNumberPosition(-10);  
  35. }  
  36. //save the document  
  37. document.saveToFile("CreateLists.docx", FileFormat.Docx_2013);  
Output
 
How To Generate Word Documents In Java
 

Add an image to Word

 
Images can beautify the document to attract more readers. Insertion of an image to Word documents can easily be done by using paragraph.appendPicture() method.
  1. //load the Word document  
  2.  Document document = new Document();  
  3.   
  4.  //add a section  
  5.  Section section = document.addSection();  
  6.   
  7.  //add a paragraph  
  8.  Paragraph paragraph = section.addParagraph();  
  9.   
  10.  //insert a picture  
  11.  DocPicture picture = paragraph.appendPicture("Image.png");  
  12.   
  13.  //set the width and height of the picture  
  14.  picture.setWidth(300f);  
  15.  picture.setHeight(200f);  
  16.   
  17.  //save the document  
  18.  document.saveToFile("InsertImage.docx", FileFormat.Docx_2013);  
Output
 
How To Generate Word Documents In Java
 
Besides creating Word documents from scratch, Spire.Doc also supports to operate the existing Word documents, such as saving Word to PDF/image, adding digital signature to Word, etc. We will introduce more Word functions on Java platform in the future. Enjoy your reading!