How to Create Table in a Word Document with Java

This brief step-by-step guide covers how to create table in a Word Document with Java. With the help of this tutorial, you can insert one or more tables to organize information as per your requirements. At the last step, the output file is saved as DOCX file but you can save it in any Word file format.

Steps to Create Table in a Word Document with Java

  1. Add Aspose.Words for Java from the Maven repository
  2. Initialize an empty Word document using Document class
  3. Initialize a new Table class instance
  4. Create a new Row in the table
  5. Create a cell and add a new paragraph inside the cell
  6. Insert table at the end of the document
  7. Save Word document with Table as a DOCX file

Using these steps we can insert table in Word document using Java. We can add information into the cells and organize the document contents programmatically using Java.

Code to Create Table in a Word Document with Java

import com.aspose.words.Cell;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.Paragraph;
import com.aspose.words.Row;
import com.aspose.words.Run;
import com.aspose.words.Table;
public class CreateTableInWordUsingJava
{
public static void main(String[] args) throws Exception { //main function for CreateTableInWordUsingJava class
// Initialize a license to avoid trial version watermark in the output Word file after adding comments
License license = new License();
license.setLicense("Aspose.Words.lic");
// Initialize a blank Word document using Document class
Document wordDocument = new Document();
// Initialize a new Table class instance
Table wordTable = new Table(wordDocument);
// Create a new Row in the Table
wordTable.getRows().add(new Row(wordDocument));
// Create single Cell in the Table Row
wordTable.getFirstRow().getCells().add(new Cell(wordDocument));
// Add a new Paragraph inside Cell
wordTable.getFirstRow().getFirstCell().appendChild(new Paragraph(wordDocument));
// Add text content inside the Table Cell
wordTable.getFirstRow().getFirstCell().getFirstParagraph().getRuns().add(new Run(wordDocument, "Text in Table Row 1 and Cell 1"));
// Insert a Table at the last portion of Word Document
wordDocument.getFirstSection().getBody().insertBefore(wordTable, wordDocument.getFirstSection().getBody().getLastParagraph());
// Save Word document with Table in DOCX format
wordDocument.save("word_table.docx");
}
}

In this Java code, we initialized a blank Word Document, then added a Table and inserted contents into a specific cell. Then the table is inserted at the end to demonstrate how to make a table in Word document using Java.

In this tutorial, we have learned how to insert table in Word document using Java. However, if you want to add a row to a table in Word document then you may refer to the article how to add rows to table in DOCX using Java.

 English