How to Build a Table in a Word Document in Java
Aspose.Words FOSS for Java builds tables from code. This guide uses DocumentBuilder to write a heading, a paragraph, and a two-cell table into a new document and saves it as DOCX, with the library from Maven Central.
Step-by-Step Guide
Step 1: Install the Package
Add the package to your build. The library needs Java 8 or later.
<dependency>
<groupId>org.aspose</groupId>
<artifactId>aspose-words-foss</artifactId>
<version>26.3.0</version>
</dependency>Step 2: Import the Classes
All classes are in the com.aspose.words package, so the example starts with import com.aspose.words.*;.
Step 3: Build the Table
startTable begins a table. Each insertCell starts a new cell, and write puts text into it. endRow finishes the row and endTable finishes the table. Before the table the recipe writes a heading and a paragraph that contains the current date.
import com.aspose.words.*;
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.HEADING_1);
builder.writeln("Quarterly Report");
builder.getParagraphFormat().setStyleIdentifier(StyleIdentifier.BODY_TEXT);
builder.writeln("Generated on " + java.time.LocalDate.now());
builder.startTable();
builder.insertCell(); builder.write("Region");
builder.insertCell(); builder.write("Revenue");
builder.endRow(); builder.endTable();
doc.save("report.docx");Common Issues and Fixes
The compiler reports cannot find symbol for Document. The com.aspose.words package is not imported. Add import com.aspose.words.*;.
The compiler reports an unreported exception. The Document constructors, Document.save and some other methods declare throws Exception. Declare it on the calling method or catch it.
The second paragraph shows a different date on each run. The example writes java.time.LocalDate.now(). Replace it with a fixed string when you need the same document every time.
Frequently Asked Questions
Which methods build a table?
startTable, insertCell, endRow, and endTable on DocumentBuilder.
Where is the document saved?
In a file named report.docx in the current working directory.
Can I check the result?
Open the file with new Document("report.docx") and read it back.