Skip to main content

Command Palette

Search for a command to run...

Create a Word Document with Java [a Complete Guide]

Published
6 min read

In today’s fast-paced economy, automated document generation has become an essential skill in the workplace. By mastering this technique, you can efficiently handle large volumes of documents, eliminate repetitive manual tasks, and minimize errors—all while boosting productivity. In this tutorial, we’ll walk you through how to create a Word document using Java that includes text, images, tables, and lists.

In this tutorial, we’ll use Spire.Doc for Java to demonstrate how to make a Word document. This professional and powerful library is designed to help developers easily and efficiently create, edit, and convert Word files.

Add Text to a Word Document in Java

Let’s start by learning how to add text to a Word document—the most essential part of any document. With Spire.Doc, you can use the appendText() method to insert the text you need. After adding it, you can easily customize the text style, size, font, and color. The following example shows how to add text to a Word document.

Code example - Add text to a Word Document:

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;
import java.awt.Color;

public class CreateSimpleDocument {
   public static void main(String[] args) {

       // Create a Document object
       Document document = new Document();

       // Add a section
       Section section = document.addSection();

       // Set page margins
       section.getPageSetup().getMargins().setAll(60f);

       // Add a title paragraph
       Paragraph title_para = section.addParagraph();
       TextRange textRange = title_para.appendText("This Is Title");
       title_para.applyStyle(BuiltinStyle.Title);
       textRange.getCharacterFormat().setFontName("Times New Roman");

       // Add a couple of heading paragraphs
       Paragraph heading_one = section.addParagraph();
       textRange = heading_one.appendText("Heading 1");
       heading_one.applyStyle(BuiltinStyle.Heading_1);
       textRange.getCharacterFormat().setFontName("Times New Roman");

       Paragraph heading_two = section.addParagraph();
       textRange = heading_two.appendText("Heading 2");
       heading_two.applyStyle(BuiltinStyle.Heading_2);
       textRange.getCharacterFormat().setFontName("Times New Roman");

       Paragraph heading_three = section.addParagraph();
       textRange = heading_three.appendText("Heading 3");
       heading_three.applyStyle(BuiltinStyle.Heading_3);
       textRange.getCharacterFormat().setFontName("Times New Roman");

       Paragraph heading_four = section.addParagraph();
       textRange = heading_four.appendText("Heading 4");
       heading_four.applyStyle(BuiltinStyle.Heading_4);
       textRange.getCharacterFormat().setFontName("Times New Roman");

       // Add a normal paragraph
       Paragraph normal_para = section.addParagraph();
       normal_para.appendText("This is a sample paragraph.");

       // Create a paragraph style
       ParagraphStyle style = new ParagraphStyle(document);
       style.setName("paraStyle");
       style.getCharacterFormat().setFontName("Times New Roman");
       style.getCharacterFormat().setFontSize(13f);
       style.getCharacterFormat().setTextColor(Color.blue);
       document.getStyles().add(style);

       // Apply the custom style to the paragraph
       normal_para.applyStyle("paraStyle");

       // Save the document
       document.saveToFile("E:/Administrator/Python1/output/AddText.docx", FileFormat.Docx);

       // Dispose resources
       document.dispose();
   }
}

Steps explained:

  • Create a Document object to start building your Word file.

  • Use Document.addSection() to insert a new section into the document.

  • Add paragraphs to the section using Section.addParagraph().

  • Apply built-in styles such as Title, Heading1, Heading2, and Heading3 to specific paragraphs with Paragraph.applyStyle().

  • Create a custom paragraph style using ParagraphStyle(), then apply it to the desired paragraph.

Add Image to Word Document

Next, let’s see how to add images to a Word document. Images make your content more visual and engaging, helping readers better understand the information. With Spire.Doc, you can easily insert local images into your document using the appendPicture() method and adjust their size and position as needed.

Code example - Insert images into a Word document:

import com.spire.doc.*;
import com.spire.doc.documents.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class CreateSimpleDocument {
   public static void main(String[] args) throws IOException {

       // Create a Document object
       Document document = new Document();

       // Add a section
       Section section = document.addSection();

       // Set page margins
       section.getPageSetup().getMargins().setAll(60f);

       // Add a paragraph
       Paragraph image_para = section.addParagraph();

       // Load an image file
       BufferedImage image =  ImageIO.read(new File("F:/备用图片/avatar-1.png"));

       // Append it to the paragraph
       image_para.appendPicture(image);

       // Save the document
       document.saveToFile("E:/Administrator/Python1/output/AddImage.docx", FileFormat.Docx);

       // Dispose resources
       document.dispose();
   }
}

Steps explained:

  • Create a Document object to begin your Word file.

  • Add a new section to the document using Document.addSection().

  • Insert a paragraph into the section with Section.addParagraph().

  • Add an image to the paragraph using Paragraph.appendPicture().

Add a Table in a Word Document Using Java

When creating documents, tables are often used to organize data or compare information, making the content clearer and easier to read. With Spire.Doc, you can quickly create tables in a Word document using the addTable() method, add rows and cells, and customize the table’s style and formatting as needed.

Code example - Add a table to a Word document:

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

public class CreateSimpleDocument {
   public static void main(String[] args) {

       // Create a Document object
       Document document = new Document();

       // Add a section
       Section section = document.addSection();

       // Set page margins
       section.getPageSetup().getMargins().setAll(60f);

       // Define table data as a 2D array
       String[][] data = {
               {"Product", "Unit Price", "Quantity", "Sub Total"},
               {"A", "$29", "120", "$3,480"},
               {"B", "$35", "110", "$3,850"},
               {"C", "$68", "140", "$9,520"}
       };

       // Add a table
       Table table = section.addTable(true);

       // Set row number and column number
       table.resetCells(data.length, data[0].length);

       // Write data to cells
       for (int r = 0; r < data.length; r++) {
           TableRow row = table.getRows().get(r);
           row.setHeight(20);
           row.setHeightType(TableRowHeightType.Exactly);

           for (int c = 0; c < data[r].length; c++) {
               TableCell cell = row.getCells().get(c);
               cell.getCellFormat().setVerticalAlignment(VerticalAlignment.Middle);
               TextRange textRange = cell.addParagraph().appendText(data[r][c]);
               textRange.getCharacterFormat().setFontName("Times New Roman");
               textRange.getCharacterFormat().setFontSize(14);
           }
       }

       // Automatically adjusts the column widths of a table to fit its contents
       table.autoFit(AutoFitBehaviorType.Auto_Fit_To_Contents);

       // Save the document to file
       document.saveToFile("E:/Administrator/Python1/output/AddTable.docx", FileFormat.Docx);

       // Dispose resources
       document.dispose();
   }
}

Steps explained:

  • Create a Document object to start your Word document.

  • Add a section to the document using Document.addSection().

  • Prepare a two-dimensional array to store your table data, including headers and values.

  • Generate a table in the section using Section.addTable().

  • Use Table.resetCells() to set the number of rows and columns according to your data.

  • Loop through the data array and add text to each cell using TableCell.addParagraph() and Paragraph.appendText().

Add a List to Word Document in Java

In addition to text and tables, lists are another common way to structure content in a document. They help organize information clearly and make key points stand out. With Spire.Doc, you can use the ListStyle class and the applyStyle() method to easily create bulleted or numbered lists and customize their appearance to fit your needs.

Code example - Add a list to a Word document:

import com.spire.doc.*;
import com.spire.doc.documents.*;
import com.spire.doc.fields.*;

public class CreateSimpleDocument {
   public static void main(String[] args) {

       // Create a Document object
       Document document = new Document();

       // Add a section
       Section section = document.addSection();

       // Set page margins
       section.getPageSetup().getMargins().setAll(60f);

       // Create a bulleted list style
       ListStyle listStyle = new ListStyle(document, ListType.Bulleted);
       listStyle.setName("bulletedList");
       listStyle.getLevels().get(0).setBulletCharacter("\u00B7");
       listStyle.getLevels().get(0).getCharacterFormat().setFontName("Symbol");
       listStyle.getLevels().get(0).setTextPosition(20);
       document.getListStyles().add(listStyle);

       // Add a paragraph
       Paragraph paragraph = section.addParagraph();
       TextRange textRange = paragraph.appendText("Fruits:");
       paragraph.getFormat().setAfterSpacing(5f);
       textRange.getCharacterFormat().setFontName("Times New Roman");
       textRange.getCharacterFormat().setFontSize(14);

       // Add another four paragraphs as bulleted list items
       String[] fruits = {"Apple", "Grape", "Pear", "Mango"};
       for (String fruit : fruits) {
           paragraph = section.addParagraph();
           textRange = paragraph.appendText(fruit);
           paragraph.getListFormat().applyStyle(listStyle.getName());
           paragraph.getListFormat().setListLevelNumber(0);
           textRange.getCharacterFormat().setFontName("Times New Roman");
           textRange.getCharacterFormat().setFontSize(14);
       }

       // Save the document to file
       document.saveToFile("E:/Administrator/Python1/output/AddList.docx", FileFormat.Docx);

       // Dispose resources
       document.dispose();
   }
}

Steps explained:

  • Create a Document object to start your Word file.

  • Add a section to the document using Document.addSection().

  • Define a list style with ListStyle().

  • Insert paragraphs into the section using Section.addParagraph().

  • Apply the defined list style to the paragraphs via Paragraph.getListFormat().applyStyle().

The Conclusion

By following the steps above, you’ve learned how to use Spire.Doc for Java to create a complete Word document with text, images, tables, and lists. With this powerful library, you can easily automate document creation and significantly boost your productivity. Whether you’re generating reports in bulk, creating contract templates, or producing dynamic content, Spire.Doc offers a reliable and efficient solution for your Java projects.