Create a Table
Aspose.Words allows users to create tables in a document from scratch and provides several different methods for doing so. This article presents details on how to add formatted tables to your document using each method, as well as a comparison of each method at the end of the article.
Default Table Styles
The newly created table is given default values similar to those 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 |
Create a Table with DocumentBuilder
In Aspose.Words, users can create a table in a document using the DocumentBuilder. The basic algorithm for creating a table is as follows:
- Start the table with StartTable
- Add a cell to the table using InsertCell – this automatically starts a new row
- Optionally, use the CellFormat property to specify cell formatting
- Insert the cell content using the appropriate DocumentBuilder methods such as Writeln, InsertImage, and others
- Repeat steps 2-4 until the row is complete
- Call EndRow to end the current row
- Optionally, use the RowFormat property to specify row formatting
- Repeat steps 2-7 until the table is complete
- Call EndTable to finish building the table
Important details:
- StartTable can also be called inside a cell, in which case it starts the creation of a nested table within the cell.
- After calling InsertCell, a new cell is created, and any content you add using other methods of the DocumentBuilder class will be added to the current cell. To create a new cell on the same row, call InsertCell again.
- If InsertCell is called immediately after EndRow and the end of a row, the table will continue on a new row.
- The EndTable method to end the table should only be called once after calling EndRow. Calling EndTable moves the cursor from the current cell to the position immediately after the table.
The process of creating a table can be clearly seen in the following picture:
The following code example shows how to create a simple table using DocumentBuilder with default formatting:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// 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(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.CreateSimpleTable.docx"); |
The following code example shows how to create a formatted table using DocumentBuilder:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Table table = builder.StartTable(); | |
builder.InsertCell(); | |
// Table wide formatting must be applied after at least one row is present in the table. | |
table.LeftIndent = 20.0; | |
// Set height and define the height rule for the header row. | |
builder.RowFormat.Height = 40.0; | |
builder.RowFormat.HeightRule = HeightRule.AtLeast; | |
builder.CellFormat.Shading.BackgroundPatternColor = Color.FromArgb(198, 217, 241); | |
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; | |
builder.Font.Size = 16; | |
builder.Font.Name = "Arial"; | |
builder.Font.Bold = true; | |
builder.CellFormat.Width = 100.0; | |
builder.Write("Header Row,\n Cell 1"); | |
// We don't need to specify this cell's width because it's inherited from the previous cell. | |
builder.InsertCell(); | |
builder.Write("Header Row,\n Cell 2"); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 200.0; | |
builder.Write("Header Row,\n Cell 3"); | |
builder.EndRow(); | |
builder.CellFormat.Shading.BackgroundPatternColor = Color.White; | |
builder.CellFormat.Width = 100.0; | |
builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center; | |
// Reset height and define a different height rule for table body. | |
builder.RowFormat.Height = 30.0; | |
builder.RowFormat.HeightRule = HeightRule.Auto; | |
builder.InsertCell(); | |
// Reset font formatting. | |
builder.Font.Size = 12; | |
builder.Font.Bold = false; | |
builder.Write("Row 1, Cell 1 Content"); | |
builder.InsertCell(); | |
builder.Write("Row 1, Cell 2 Content"); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 200.0; | |
builder.Write("Row 1, Cell 3 Content"); | |
builder.EndRow(); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 100.0; | |
builder.Write("Row 2, Cell 1 Content"); | |
builder.InsertCell(); | |
builder.Write("Row 2, Cell 2 Content"); | |
builder.InsertCell(); | |
builder.CellFormat.Width = 200.0; | |
builder.Write("Row 2, Cell 3 Content."); | |
builder.EndRow(); | |
builder.EndTable(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.FormattedTable.docx"); |
The following code example shows how to insert a nested table using DocumentBuilder:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
Cell cell = builder.InsertCell(); | |
builder.Writeln("Outer Table Cell 1"); | |
builder.InsertCell(); | |
builder.Writeln("Outer Table Cell 2"); | |
// This call is important 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.FirstParagraph); | |
// Build the inner table. | |
builder.InsertCell(); | |
builder.Writeln("Inner Table Cell 1"); | |
builder.InsertCell(); | |
builder.Writeln("Inner Table Cell 2"); | |
builder.EndTable(); | |
doc.Save(ArtifactsDir + "WorkingWithTables.NestedTable.docx"); |
Create a Table via DOM (Document Object Model)
You can insert tables directly into the DOM by adding a new Table node at a specific position.
Please note that immediately after the table node creation, the table itself will be completely empty, that is it does not yet contain rows and cells. To insert rows and cells into a table, add the appropriate Row and Cell child nodes to the DOM.
The following code example shows how to build a new table from scratch by adding the appropriate child nodes to the document tree:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
// We start by creating the table object. Note that 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); | |
doc.FirstSection.Body.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. | |
// 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 algorithm. | |
Row row = new Row(doc); | |
row.RowFormat.AllowBreakAcrossPages = true; | |
table.AppendChild(row); | |
Cell cell = new Cell(doc); | |
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue; | |
cell.CellFormat.Width = 80; | |
cell.AppendChild(new Paragraph(doc)); | |
cell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 1 Text")); | |
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.Clone(false)); | |
row.LastCell.AppendChild(new Paragraph(doc)); | |
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text")); | |
// We can now apply any auto fit settings. | |
table.AutoFit(AutoFitBehavior.FixedColumnWidths); | |
doc.Save(ArtifactsDir + "WorkingWithTables.InsertTableDirectly.docx"); |
Create a Table from HTML
Aspose.Words supports inserting content into a document from an HTML source using the InsertHtml method. The input can be a complete HTML page or just a partial snippet.
Using the InsertHtml method, users can insert tables into the document via table tags like <table>
, <tr>
, <td>
.
The following code example shows how to insert a table into a document from a string containing HTML tags:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(); | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// 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(ArtifactsDir + "WorkingWithTables.InsertTableFromHtml.docx"); |
Insert a Copy of an Existing Table
There are often times when you need to create a table based on an already existing table in a document. The easiest way to duplicate a table while retaining all formatting is to clone the Table node using the Clone method.
The same technique can be used to add copies of an existing row or cell to a table.
The following code example shows how to duplicate a table using node constructors:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(MyDir + "Tables.docx"); | |
Table table = (Table) doc.GetChild(NodeType.Table, 0, true); | |
// Clone the table and insert it into the document after the original. | |
Table tableClone = (Table) table.Clone(true); | |
table.ParentNode.InsertAfter(tableClone, table); | |
// Insert an empty paragraph between the two tables, | |
// or else they will be combined into one upon saving this has to do with document validation. | |
table.ParentNode.InsertAfter(new Paragraph(doc), table); | |
doc.Save(ArtifactsDir + "WorkingWithTables.CloneCompleteTable.docx"); |
The following code example shows how to clone the last row of a table and append it to the table:
// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git. | |
Document doc = new Document(MyDir + "Tables.docx"); | |
Table table = (Table) doc.GetChild(NodeType.Table, 0, true); | |
Row clonedRow = (Row) table.LastRow.Clone(true); | |
// Remove all content from the cloned row's cells. This makes the row ready for new content to be inserted into. | |
foreach (Cell cell in clonedRow.Cells) | |
cell.RemoveAllChildren(); | |
table.AppendChild(clonedRow); | |
doc.Save(ArtifactsDir + "WorkingWithTables.CloneLastRow.docx"); |
If you are looking at creating tables in a document that grow dynamically with each record from your data source, then the above method is not advised. Instead, the desired output is more easily achieved by using Mail merge with regions. You can learn more about this technique in the Mail Merge with Regions section.
Compare Ways to Create a Table
Aspose.Words provides several methods to create new tables in a document. Each method has its own advantages and disadvantages, so the choice of which to use often depends on the specific situation.
Let’s take a closer look at these ways of creating tables and compare their pros and cons:
Method | Advantages | Disadvantages |
---|---|---|
Via DocumentBuilder |
The standard method for inserting tables and other document content | Sometimes difficult to create many varieties of tables at the same time with the same builder instance |
Via DOM | Fits in better with surrounding code that creates and inserts nodes directly into the DOM without using a DocumentBuilder | The table is created “empty”: before performing most operations, you must call EnsureMinimum to create any missing child nodes |
From HTML | Can create a new table from HTML source using tags like <table> , <tr> , <td> |
Not all possible Microsoft Word table formats can be applied to HTML |
Cloning an existing table | You can create a copy of an existing table while retaining all row and cell formatting | The appropriate child nodes must be removed before the table is ready for use |