Aspose.Words provides several different methods to create new tables in a document. This article presents the full details of how to insert formatted tables using each technique as well as a comparison of each technique at the end of the article.
A newly created table is given similar defaults as used in Microsoft Word:
Table Property |
Default in Aspose.Words |
Border Style |
Single |
Border Width |
1/2 pt |
Border Color |
Black |
Left and Right Padding |
5.4 pts |
AutoFit Mode |
AutoFit to Window |
Allow AutoFit |
True |
A table can be inline where it is tightly positioned or can be floating where it can be positioned anywhere on the page. By default, Aspose.Words always creates inline tables.
In Aspose.Words a table is normally inserted using DocumentBuilder. The following methods are used to build a table. Other methods will also be used to insert content into the table cells.
· DocumentBuilder.StartTable
· DocumentBuilder.InsertCell
· DocumentBuilder.EndRow
· DocumentBuilder.EndTable
· DocumentBuilder.Writeln
Operation |
Description |
Table State |
DocumentBuilder.StartTable |
Starts building a new table at the current cursor position. |
|
DocumentBuilder.InsertCell |
Inserts a new row and cell into the table. |
|
DocumentBuilder.Writeln |
Writes some text into the current cell. |
|
DocumentBuilder.InsertCell |
Appends a new cell at the end of the current row. |
|
DocumentBuilder.Writeln |
Writes some text into the current cell (now the second cell). |
|
DocumentBuilder.EndRow |
Instructs the builder to end the current row and to begin a new row with the next call to DocumentBuilder.InsertCell. |
|
DocumentBuilder.InsertCell |
Creates a new row and inserts a new cell. |
|
DocumentBuilder.Writeln |
Inserts some text into the first cell of the second row. |
|
DocumentBuilder.EndTable |
Called to finish off building the table. The builder cursor will now point outside the table ready to insert content after the table. |
|
Example
Shows how to create a simple table using DocumentBuilder with default formatting.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// We call this method to start building the table.
builder.startTable();
builder.insertCell();
builder.write("Row 1, Cell 1 Content.");
// Build the second cell
builder.insertCell();
builder.write("Row 1, Cell 2 Content.");
// Call the following method to end the row and start a new row.
builder.endRow();
// Build the first cell of the second row.
builder.insertCell();
builder.write("Row 2, Cell 1 Content");
// Build the second cell.
builder.insertCell();
builder.write("Row 2, Cell 2 Content.");
builder.endRow();
// Signal that we have finished building the table.
builder.endTable();
// Save the document to disk.
doc.save(getMyDir() + "DocumentBuilder.CreateSimpleTable Out.doc");
The result of the above code is a table inserted in to the document which contains four cells and some text.
Example
Shows how to create a formatted table using DocumentBuilder
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
Table table = builder.startTable();
// Make the header row.
builder.insertCell();
// Set the left indent for the table. Table wide formatting must be applied after
// at least one row is present in the table.
table.setLeftIndent(20.0);
// Set height and define the height rule for the header row.
builder.getRowFormat().setHeight(40.0);
builder.getRowFormat().setHeightRule(HeightRule.AT_LEAST);
// Some special features for the header row.
builder.getCellFormat().getShading().setBackgroundPatternColor(new Color(198, 217, 241));
builder.getParagraphFormat().setAlignment(ParagraphAlignment.CENTER);
builder.getFont().setSize(16);
builder.getFont().setName("Arial");
builder.getFont().setBold (true);
builder.getCellFormat().setWidth(100.0);
builder.write("Header Row,\n Cell 1");
// We don't need to specify the width of this cell because it's inherited from the previous cell.
builder.insertCell();
builder.write("Header Row,\n Cell 2");
builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Header Row,\n Cell 3");
builder.endRow();
// Set features for the other rows and cells.
builder.getCellFormat().getShading().setBackgroundPatternColor(Color.WHITE);
builder.getCellFormat().setWidth(100.0);
builder.getCellFormat().setVerticalAlignment(CellVerticalAlignment.CENTER);
// Reset height and define a different height rule for table body
builder.getRowFormat().setHeight(30.0);
builder.getRowFormat().setHeightRule(HeightRule.AUTO);
builder.insertCell();
// Reset font formatting.
builder.getFont().setSize(12);
builder.getFont().setBold(false);
// Build the other cells.
builder.write("Row 1, Cell 1 Content");
builder.insertCell();
builder.write("Row 1, Cell 2 Content");
builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Row 1, Cell 3 Content");
builder.endRow();
builder.insertCell();
builder.getCellFormat().setWidth(100.0);
builder.write("Row 2, Cell 1 Content");
builder.insertCell();
builder.write("Row 2, Cell 2 Content");
builder.insertCell();
builder.getCellFormat().setWidth(200.0);
builder.write("Row 2, Cell 3 Content.");
builder.endRow();
builder.endTable();
doc.save(getMyDir() + "DocumentBuilder.CreateFormattedTable Out.doc");
The result is a table which is formatted with some cell shading and different cell alignment.
Example
Shows how to insert a nested table using DocumentBuilder.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Build the outer table.
Cell cell = builder.insertCell();
builder.writeln("Outer Table Cell 1");
builder.insertCell();
builder.writeln("Outer Table Cell 2");
// This call is important in order to create a nested table within the first table
// Without this call the cells inserted below will be appended to the outer table.
builder.endTable();
// Move to the first cell of the outer table.
builder.moveTo(cell.getFirstParagraph());
// Build the inner table.
builder.insertCell();
builder.writeln("Inner Table Cell 1");
builder.insertCell();
builder.writeln("Inner Table Cell 2");
builder.endTable();
doc.save(getMyDir() + "DocumentBuilder.InsertNestedTable Out.doc");
This will produce a table within another table. This is often referred to as a nested table.
Additionally you can insert tables directly into the DOM at a particular node position. The same table defaults are used as when using a DocumentBuilder to create a table. However you must take into account that the table will initially be completely empty (i.e contains no child rows yet). In order to build the table you will first need to add the appropriate child nodes.
Example
Shows how to insert a table using the constructors of nodes.
[Java]
Document doc = new Document();
// We start by creating the table object. Note how we must pass the document object
// to the constructor of each node. This is because every node we create must belong
// to some document.
Table table = new Table(doc);
// Add the table to the document.
doc.getFirstSection().getBody().appendChild(table);
// Here we could call EnsureMinimum to create the rows and cells for us. This method is used
// to ensure that the specified node is valid, in this case a valid table should have at least one
// row and one cell, therefore this method creates them for us.
// Instead we will handle creating the row and table ourselves. This would be the best way to do this
// if we were creating a table inside an algorthim for example.
Row row = new Row(doc);
row.getRowFormat().setAllowBreakAcrossPages(true);
table.appendChild(row);
// We can now apply any auto fit settings.
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);
// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.getCellFormat().getShading().setBackgroundPatternColor(Color.BLUE);
cell.getCellFormat().setWidth(80);
// Add a paragraph to the cell as well as a new run with some text.
cell.appendChild(new Paragraph(doc));
cell.getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 1 Text"));
// Add the cell to the row.
row.appendChild(cell);
// We would then repeat the process for the other cells and rows in the table.
// We can also speed things up by cloning existing cells and rows.
row.appendChild(cell.deepClone(false));
row.getLastCell().appendChild(new Paragraph(doc));
row.getLastCell().getFirstParagraph().appendChild(new Run(doc, "Row 1, Cell 2 Text"));
doc.save(getMyDir() + "Table.InsertTableUsingNodes Out.doc");
Often there are times when you have an existing table in a document and would like to add a copy of this table then apply some modifications. The easiest way to duplicate a table while retaining all formatting is to clone the table node using the Table.Clone method.
Example
Shows how to make a clone of a table in the document and insert it after the original table.
[Java]
Document doc = new Document(getMyDir() + "Table.SimpleTable.doc");
// Retrieve the first table in the document.
Table table = (Table)doc.getChild(NodeType.TABLE, 0, true);
// Create a clone of the table.
Table tableClone = (Table)table.deepClone(true);
// Insert the cloned table into the document after the original
table.getParentNode().insertAfter(tableClone, table);
// Insert an empty paragraph between the two tables or else they will be combined into one
// upon save. This has to do with document validation.
table.getParentNode().insertAfter(new Paragraph(doc), table);
doc.save(getMyDir() + "Table.CloneTableAndInsert Out.doc");
If the new table is to include different content you will need to first clear the existing content from the table first.
Example
Shows how to remove all content from the cells of a cloned table.
[Java]
for (Cell cell : (Iterable<Cell>) tableClone.getChildNodes(NodeType.CELL, true))
cell.removeAllChildren();
The same technique can be used to add copies of an existing row to a table.
Example
Shows how to make a clone of the last row of a table and append it to the table.
[Java]
Document doc = new Document(getMyDir() + "Table.SimpleTable.doc");
// Retrieve the first table in the document.
Table table = (Table)doc.getChild(NodeType.TABLE, 0, true);
// Clone the last row in the table.
Row clonedRow = (Row)table.getLastRow().deepClone(true);
// Remove all content from the cloned row's cells. This makes the row ready for
// new content to be inserted into.
for(Cell cell : clonedRow.getCells())
cell.removeAllChildren();
// Add the row to the end of the table.
table.appendChild(clonedRow);
doc.save(getMyDir() + "Table.AddCloneRowToTable Out.doc");
If you are looking at creating tables in document which dynamically grow with each record from your data source, then the above method is not advised.
Instead the desired output is achieved more easily by using Mail Merge with Regions. You can learn more about this technique under Mail Merge with Regions Explained.
Aspose.Words supports inserting content into a document from an HTML source by using the DocumentBuilder.InsertHtml method. The input can be a full HTML page or just a partial snippet. Using this method we can insert tables into our document by using table elements e.g <table>, <tr>, <td>.
Example
Shows how to insert a table in a document from a string containing HTML tags.
[Java]
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
// Insert the table from HTML. Note that AutoFitSettings does not apply to tables
// inserted from HTML.
builder.insertHtml("<table>" +
"<tr>" +
"<td>Row 1, Cell 1</td>" +
"<td>Row 1, Cell 2</td>" +
"</tr>" +
"<tr>" +
"<td>Row 2, Cell 2</td>" +
"<td>Row 2, Cell 2</td>" +
"</tr>" +
"</table>");
doc.save(getMyDir() + "DocumentBuilder.InsertTableFromHtml Out.doc");
As described above, Aspose.Words provides several methods for inserting new tables into a document. Each have their advantages and disadvantages, so often the choice of which to use depends on your situation. The table below can give you an idea of each technique.
Method |
Advantages |
Disadvantages |
DocumentBuilder (DocumentBuilder.StartTable) |
Standard method of inserting tables and other document content.
|
Sometimes hard to create many varieties of tables at the same time with the same instance of the builder. |
Table (Table.#ctor) |
Fits in better with surronding code that creates and inserts nodes directly into the DOM without the use of DocumentBuilder. |
Table is created “blank”. Before most operations are performed Table.EnsureMinimum must be called to create any missing child nodes. |
Cloning (Table.Clone) |
Can create a copy of an existing table while retaining all formatting on rows and cells. |
The appropriate child nodes must be removed before the table is ready for use. |
From an HTML source. (DocumentBuilder.InsertHtml) |
Can create a new table from HTML source e.g the <table>, <tr>, <td> tags |
Not all possible formatting on a Microsoft Word table can be applied in HTML. |