Working with Tables

Overview

A table is built with DocumentBuilder: you start a table, insert a cell, write its content, finish the row, and finish the table. This page shows the whole sequence in one recipe that also writes a heading and a paragraph before the table, then saves the document as DOCX.


Prerequisites

RequirementDetail
Java8 or later
DependencyThe package from Installation
Importimport com.aspose.words.*;

Build a Table with DocumentBuilder

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. The recipe below writes two cells, “Region” and “Revenue”, and saves the result:

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");

Tips and Best Practices

  • Call endRow for every row and endTable once, after the last row.
  • Write the cell content right after insertCell, before the next insertCell.
  • Reopen the saved file with new Document("report.docx") to check the result.

Common Issues

IssueCauseFix
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.

FAQ

Which methods build a table?

startTable, insertCell, endRow, and endTable on DocumentBuilder.

Does the example write anything besides the table?

Yes. It first writes a heading and a paragraph that contains the current date, using java.time.LocalDate.

Where is the table saved?

In a file named report.docx, in the current working directory.


API Reference Summary

Class / MethodDescription
DocumentBuilderProvides methods to insert text, images and other content, specify font, paragraph and section formatting.
DocumentBuilder.startTable()Starts a table in the document.
DocumentBuilder.insertCell()Inserts a table cell into the document.
DocumentBuilder.endRow()Ends a table row in the document.
DocumentBuilder.endTable()Ends a table in the document.
TableRepresents a table in a Word document.

Related Guides

See Also