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. //Add a section
  4. Section section = document.addSection();
  5. //Add two paragraphs to the section
  6. Paragraph para1 = section.addParagraph();
  7. para1.appendText("How to create Word document in Java");
  8. Paragraph para2 = section.addParagraph();
  9. para2.appendText("This article demonstrate how to create Word document with text, images, lists and tables.");
  10. //Set title style for paragraph 1
  11. ParagraphStyle style1 = new ParagraphStyle(document);
  12. style1.setName("titleStyle");
  13. style1.getCharacterFormat().setBold(true);
  14. style1.getCharacterFormat().setTextColor(Color.BLUE);
  15. style1.getCharacterFormat().setFontName("Arial");
  16. style1.getCharacterFormat().setFontSize(12f);
  17. document.getStyles().add(style1);
  18. para1.applyStyle("titleStyle");
  19. //Set style for paragraph 2
  20. ParagraphStyle style2 = new ParagraphStyle(document);
  21. style2.setName("paraStyle");
  22. style2.getCharacterFormat().setFontName("Arial");
  23. style2.getCharacterFormat().setFontSize(11f);
  24. document.getStyles().add(style2);
  25. para2.applyStyle("paraStyle");
  26. //Horizontally align paragraph 1 to center
  27. para1.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
  28. //Set first-line indent for paragraph 2
  29. para2.getFormat().setFirstLineIndent(12f);
  30. //Set spaces after paragraph 1 and 2
  31. para1.getFormat().setAfterSpacing(15f);
  32. para2.getFormat().setAfterSpacing(10f);
  33. //Save the document
  34. 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. //Add a section
  4. Section section = document.addSection();
  5. //Define data to create table
  6. String[] header = {"Name", "Gender"};
  7. String[][] data =
  8. {
  9. new String[]{"Winny", "Female"},
  10. new String[]{"Lois", "Female"},
  11. new String[]{"Jois", "Female"},
  12. new String[]{"Moon", "Male"},
  13. new String[]{"Vinit", "Female"},
  14. };
  15. //Add a table
  16. Table table = section.addTable();
  17. table.resetCells(data.length + 1, header.length);
  18. table.applyStyle(DefaultTableStyle.Colorful_List);
  19. table.getTableFormat().getBorders().setBorderType(BorderStyle.Single);
  20. //Set the first row as table header and add data
  21. TableRow row = table.getRows().get(0);
  22. row.isHeader(true);
  23. row.setHeight(20);
  24. row.setHeightType(TableRowHeightType.Exactly);
  25. row.getRowFormat().setBackColor(Color.gray);
  26. for (int i = 0; i < header.length; i++) {
  27. row.getCells().get(i).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
  28. Paragraph p = row.getCells().get(i).addParagraph();
  29. p.getFormat().setHorizontalAlignment(HorizontalAlignment.Center);
  30. TextRange range1 = p.appendText(header[i]);
  31. range1.getCharacterFormat().setFontName("Arial");
  32. range1.getCharacterFormat().setFontSize(12f);
  33. range1.getCharacterFormat().setBold(true);
  34. }
  35. //Add data to the rest of rows
  36. for (int r = 0; r < data.length; r++) {
  37. TableRow dataRow = table.getRows().get(r + 1);
  38. dataRow.setHeight(25);
  39. dataRow.setHeightType(TableRowHeightType.Exactly);
  40. dataRow.getRowFormat().setBackColor(Color.white);
  41. for (int c = 0; c < data[r].length; c++) {
  42. dataRow.getCells().get(c).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
  43. TextRange range2 = dataRow.getCells().get(c).addParagraph().appendText(data[r][c]);
  44. range2.getCharacterFormat().setFontName("Arial");
  45. range2.getCharacterFormat().setFontSize(10f);
  46. }
  47. }
  48. //Set background color for cells
  49. for (int j = 1; j < table.getRows().getCount(); j++) {
  50. if (j % 2 == 0) {
  51. TableRow row2 = table.getRows().get(j);
  52. for (int f = 0; f < row2.getCells().getCount(); f++) {
  53. row2.getCells().get(f).getCellFormat().setBackColor(new Color(173, 216, 230));
  54. }
  55. }
  56. }
  57. //Save the document
  58. 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. //add a section
  4. Section section = document.addSection();
  5. //add a paragraph
  6. Paragraph paragraph = section.addParagraph();
  7. //insert a picture
  8. DocPicture picture = paragraph.appendPicture("Image.png");
  9. //set the width and height of the picture
  10. picture.setWidth(300f);
  11. picture.setHeight(200f);
  12. //save the document
  13. 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!