Table Class
Represents a table in a Word document.
Inheritance Hierarchy

Namespace: Aspose.Words.Tables
Assembly: Aspose.Words (in Aspose.Words.dll) Version: 17.8
Syntax
public class Table : CompositeNode

The Table type exposes the following members.

Constructors
  NameDescription
Public methodCode exampleTable
Initializes a new instance of the Table class.
Properties
  NameDescription
Public propertyCode exampleAlignment
Specifies how an inline table is aligned in the document.
Public propertyCode exampleAllowAutoFit
Allows Microsoft Word and Aspose.Words to automatically resize cells in a table to fit their contents.
Public propertyBidi
Gets or sets whether this is a right-to-left table.
Public propertyCode exampleBottomPadding
Gets or sets the amount of space (in points) to add below the contents of cells.
Public propertyCellSpacing
Gets or sets the amount of space (in points) between the cells.
Public propertyCode exampleChildNodes
Gets all immediate child nodes of this node.
(Inherited from CompositeNode.)
Public propertyCount
Gets the number of immediate children of this node.
(Inherited from CompositeNode.)
Public propertyDistanceBottom
Gets distance between table bottom and the surrounding text, in points.
Public propertyDistanceLeft
Gets distance between table left and the surrounding text, in points.
Public propertyDistanceRight
Gets distance between table right and the surrounding text, in points.
Public propertyDistanceTop
Gets distance between table top and the surrounding text, in points.
Public propertyCode exampleDocument
Gets the document to which this node belongs.
(Inherited from Node.)
Public propertyCode exampleFirstChild
Gets the first child of the node.
(Inherited from CompositeNode.)
Public propertyCode exampleFirstRow
Returns the first Row node in the table.
Public propertyCode exampleHasChildNodes
Returns true if this node has any child nodes.
(Inherited from CompositeNode.)
Public propertyCode exampleIsComposite
Returns true as this node can have child nodes.
(Inherited from CompositeNode.)
Public propertyCode exampleLastChild
Gets the last child of the node.
(Inherited from CompositeNode.)
Public propertyCode exampleLastRow
Returns the last Row node in the table.
Public propertyCode exampleLeftIndent
Gets or sets the value that represents the left indent of the table.
Public propertyCode exampleLeftPadding
Gets or sets the amount of space (in points) to add to the left of the contents of cells.
Public propertyCode exampleNextSibling
Gets the node immediately following this node.
(Inherited from Node.)
Public propertyCode exampleNodeType
Returns NodeType.Table.
(Overrides NodeNodeType.)
Public propertyCode exampleParentNode
Gets the immediate parent of this node.
(Inherited from Node.)
Public propertyCode examplePreferredWidth
Gets or sets the table preferred width.
Public propertyCode examplePreviousSibling
Gets the node immediately preceding this node.
(Inherited from Node.)
Public propertyCode exampleRange
Returns a Range object that represents the portion of a document that is contained in this node.
(Inherited from Node.)
Public propertyCode exampleRightPadding
Gets or sets the amount of space (in points) to add to the right of the contents of cells.
Public propertyCode exampleRows
Provides typed access to the rows of the table.
Public propertyStyle
Gets or sets the table style applied to this table.
Public propertyCode exampleStyleIdentifier
Gets or sets the locale independent style identifier of the table style applied to this table.
Public propertyStyleName
Gets or sets the name of the table style applied to this table.
Public propertyCode exampleStyleOptions
Gets or sets bit flags that specify how a table style is applied to this table.
Public propertyTextWrapping
Get or sets TextWrapping TextWrapping for table.
Public propertyCode exampleTopPadding
Gets or sets the amount of space (in points) to add above the contents of cells.
Methods
  NameDescription
Public methodCode exampleAccept
Accepts a visitor.
(Overrides NodeAccept(DocumentVisitor).)
Protected methodAcceptChildren (Inherited from CompositeNode.)
Protected methodAcceptCore (Inherited from CompositeNode.)
Public methodCode exampleAppendChild
Adds the specified node to the end of the list of child nodes for this node.
(Inherited from CompositeNode.)
Public methodCode exampleAutoFit
Resizes the table and cells according to the specified auto fit behavior.
Public methodCode exampleClearBorders
Removes all table and cell borders on this table.
Public methodClearShading
Removes all shading on the table.
Public methodCode exampleClone
Creates a duplicate of the node.
(Inherited from Node.)
Protected methodCoreRemoveSelfOnly (Inherited from CompositeNode.)
Public methodCreateNavigator
Reserved for system use. IXPathNavigable.
(Inherited from CompositeNode.)
Public methodCode exampleEnsureMinimum
If the table has no rows, creates and appends one Row.
Public methodEquals
Determines whether the specified Object is equal to the current Object.
(Inherited from Object.)
Protected methodFinalize
Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.
(Inherited from Object.)
Public methodGetAncestor(Type)
Gets the first ancestor of the specified object type.
(Inherited from Node.)
Public methodCode exampleGetAncestor(NodeType)
Gets the first ancestor of the specified NodeType.
(Inherited from Node.)
Public methodCode exampleGetChild
Returns an Nth child node that matches the specified type.
(Inherited from CompositeNode.)
Public methodCode exampleGetChildNodes(NodeType, Boolean)
Returns a live collection of child nodes that match the specified type.
(Inherited from CompositeNode.)
Public methodGetChildNodes(NodeType, Boolean, Boolean) Obsolete.
Returns a collection of child nodes that match the specified type.
(Inherited from CompositeNode.)
Public methodCode exampleGetEnumerator
Provides support for the for each style iteration over the child nodes of this node.
(Inherited from CompositeNode.)
Public methodGetHashCode
Serves as a hash function for a particular type.
(Inherited from Object.)
Public methodCode exampleGetText
Gets the text of this node and of all its children.
(Inherited from CompositeNode.)
Public methodGetType
Gets the type of the current instance.
(Inherited from Object.)
Public methodCode exampleIndexOf
Returns the index of the specified child node in the child node array.
(Inherited from CompositeNode.)
Public methodCode exampleInsertAfter
Inserts the specified node immediately after the specified reference node.
(Inherited from CompositeNode.)
Public methodInsertBefore
Inserts the specified node immediately before the specified reference node.
(Inherited from CompositeNode.)
Protected methodMemberwiseClone
Creates a shallow copy of the current Object.
(Inherited from Object.)
Public methodCode exampleNextPreOrder
Gets next node according to the pre-order tree traversal algorithm.
(Inherited from Node.)
Public methodCode examplePrependChild
Adds the specified node to the beginning of the list of child nodes for this node.
(Inherited from CompositeNode.)
Public methodPreviousPreOrder
Gets the previous node according to the pre-order tree traversal algorithm.
(Inherited from Node.)
Public methodCode exampleRemove
Removes itself from the parent.
(Inherited from Node.)
Public methodCode exampleRemoveAllChildren
Removes all the child nodes of the current node.
(Inherited from CompositeNode.)
Public methodCode exampleRemoveChild
Removes the specified child node.
(Inherited from CompositeNode.)
Public methodCode exampleRemoveSmartTags
Removes all SmartTag descendant nodes of the current node.
(Inherited from CompositeNode.)
Public methodCode exampleSelectNodes
Selects a list of nodes matching the XPath expression.
(Inherited from CompositeNode.)
Public methodCode exampleSelectSingleNode
Selects the first Node that matches the XPath expression.
(Inherited from CompositeNode.)
Public methodCode exampleSetBorder
Sets the specified table border to the specified line style, width and color.
Public methodCode exampleSetBorders
Sets all table borders to the specified line style, width and color.
Public methodCode exampleSetShading
Sets shading to the specified values on all cells in the table.
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Public methodCode exampleToString(SaveFormat)
Exports the content of the node into a string in the specified format.
(Inherited from Node.)
Public methodCode exampleToString(SaveOptions)
Exports the content of the node into a string using the specified save options.
(Inherited from Node.)
Public methodToTxt Obsolete.
Exports the content of the node into a string in plain text format.
(Inherited from Node.)
Remarks

Table is a block-level node and can be a child of classes derived from Story or InlineStory.

Table can contain one or more Row nodes.

A minimal valid table needs to have at least one Row.

Examples
Shows how to remove all borders from a table.
[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Remove all borders from the first table in the document.
Table table = (Table)doc.GetChild(NodeType.Table, 0, true);

// Clear the borders all cells in the table.
table.ClearBorders();

doc.Save(MyDir + "Table.ClearBorders Out.doc");
[Visual Basic]

Dim doc As New Document(MyDir & "Table.Document.doc")

' Remove all borders from the first table in the document.
Dim table As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)

' Clear the borders all cells in the table.
table.ClearBorders()

doc.Save(MyDir & "Table.ClearBorders Out.doc")
Examples
Shows how to combine the rows from two tables into one.
[C#]

// Load the document.
Document doc = new Document(MyDir + "Table.Document.doc");

// Get the first and second table in the document.
// The rows from the second table will be appended to the end of the first table.
Table firstTable = (Table)doc.GetChild(NodeType.Table, 0, true);
Table secondTable = (Table)doc.GetChild(NodeType.Table, 1, true);

// Append all rows from the current table to the next.
// Due to the design of tables even tables with different cell count and widths can be joined into one table.
while (secondTable.HasChildNodes)
    firstTable.Rows.Add(secondTable.FirstRow);

// Remove the empty table container.
secondTable.Remove();

doc.Save(MyDir + "Table.CombineTables Out.doc");
[Visual Basic]

' Load the document.
Dim doc As New Document(MyDir & "Table.Document.doc")

' Get the first and second table in the document.
' The rows from the second table will be appended to the end of the first table.
Dim firstTable As Table = CType(doc.GetChild(NodeType.Table, 0, True), Table)
Dim secondTable As Table = CType(doc.GetChild(NodeType.Table, 1, True), Table)

' Append all rows from the current table to the next.
' Due to the design of tables even tables with different cell count and widths can be joined into one table.
Do While secondTable.HasChildNodes
    firstTable.Rows.Add(secondTable.FirstRow)
Loop

' Remove the empty table container.
secondTable.Remove()

doc.Save(MyDir & "Table.CombineTables Out.doc")
Examples
Shows how to build a formatted table that contains 2 rows and 2 columns.
[C#]

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

Table table = builder.StartTable();

// Insert a cell
builder.InsertCell();
// Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
builder.Write("This is row 1 cell 1");

// Insert a cell
builder.InsertCell();
builder.Write("This is row 1 cell 2");

builder.EndRow();

// Insert a cell
builder.InsertCell();

// Apply new row formatting
builder.RowFormat.Height = 100;
builder.RowFormat.HeightRule = HeightRule.Exactly;

builder.CellFormat.Orientation = TextOrientation.Upward;
builder.Writeln("This is row 2 cell 1");

// Insert a cell
builder.InsertCell();
builder.CellFormat.Orientation = TextOrientation.Downward;
builder.Writeln("This is row 2 cell 2");

builder.EndRow();

builder.EndTable();
[Visual Basic]

Dim doc As New Document()
Dim builder As New DocumentBuilder(doc)

Dim table As Table = builder.StartTable()

' Insert a cell
builder.InsertCell()
' Use fixed column widths.
table.AutoFit(AutoFitBehavior.FixedColumnWidths)

builder.CellFormat.VerticalAlignment = CellVerticalAlignment.Center
builder.Write("This is row 1 cell 1")

' Insert a cell
builder.InsertCell()
builder.Write("This is row 1 cell 2")

builder.EndRow()

' Insert a cell
builder.InsertCell()

' Apply new row formatting
builder.RowFormat.Height = 100
builder.RowFormat.HeightRule = HeightRule.Exactly

builder.CellFormat.Orientation = TextOrientation.Upward
builder.Writeln("This is row 2 cell 1")

' Insert a cell
builder.InsertCell()
builder.CellFormat.Orientation = TextOrientation.Downward
builder.Writeln("This is row 2 cell 2")

builder.EndRow()

builder.EndTable()
Examples
Shows how to iterate through all tables in the document and display the content from each cell.
[C#]

Document doc = new Document(MyDir + "Table.Document.doc");

// Here we get all tables from the Document node. You can do this for any other composite node
// which can contain block level nodes. For example you can retrieve tables from header or from a cell
// containing another table (nested tables).
NodeCollection tables = doc.GetChildNodes(NodeType.Table, true);

// Iterate through all tables in the document
foreach (Table table in tables)
{
    // Get the index of the table node as contained in the parent node of the table
    int tableIndex = table.ParentNode.ChildNodes.IndexOf(table);
    Console.WriteLine("Start of Table {0}", tableIndex);

    // Iterate through all rows in the table
    foreach (Row row in table.Rows)
    {
        int rowIndex = table.Rows.IndexOf(row);
        Console.WriteLine("\tStart of Row {0}", rowIndex);

        // Iterate through all cells in the row
        foreach (Cell cell in row.Cells)
        {
            int cellIndex = row.Cells.IndexOf(cell);
            // Get the plain text content of this cell.
            string cellText = cell.ToString(SaveFormat.Text).Trim();
            // Print the content of the cell.
            Console.WriteLine("\t\tContents of Cell:{0} = \"{1}\"", cellIndex, cellText);
        }
        //Console.WriteLine();
        Console.WriteLine("\tEnd of Row {0}", rowIndex);
    }
    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
[Visual Basic]

Dim doc As New Document(MyDir & "Table.Document.doc")

' Here we get all tables from the Document node. You can do this for any other composite node
' which can contain block level nodes. For example you can retrieve tables from header or from a cell
' containing another table (nested tables).
Dim tables As NodeCollection = doc.GetChildNodes(NodeType.Table, True)

' Iterate through all tables in the document
For Each table As Table In tables
    ' Get the index of the table node as contained in the parent node of the table
    Dim tableIndex As Integer = table.ParentNode.ChildNodes.IndexOf(table)
    Console.WriteLine("Start of Table {0}", tableIndex)

    ' Iterate through all rows in the table
    For Each row As Row In table.Rows
        Dim rowIndex As Integer = table.Rows.IndexOf(row)
        Console.WriteLine(Constants.vbTab & "Start of Row {0}", rowIndex)

        ' Iterate through all cells in the row
        For Each cell As Cell In row.Cells
            Dim cellIndex As Integer = row.Cells.IndexOf(cell)
            ' Get the plain text content of this cell.
            Dim cellText As String = cell.ToString(SaveFormat.Text).Trim()
            ' Print the content of the cell.
            Console.WriteLine(Constants.vbTab + Constants.vbTab & "Contents of Cell:{0} = ""{1}""", cellIndex, cellText)
        Next cell
        'Console.WriteLine();
        Console.WriteLine(Constants.vbTab & "End of Row {0}", rowIndex)
    Next row
    Console.WriteLine("End of Table {0}", tableIndex)
    Console.WriteLine()
Next table
Examples
Shows how to build a nested table without using DocumentBuilder.
[C#]

public void NestedTablesUsingNodeConstructors()
{
    Document doc = new Document();

    // Create the outer table with three rows and four columns.
    Table outerTable = CreateTable(doc, 3, 4, "Outer Table");
    // Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable);

    // Create another table with two rows and two columns.
    Table innerTable = CreateTable(doc, 2, 2, "Inner Table");
    // Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable);

    doc.Save(MyDir + "Table.CreateNestedTable Out.doc");

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, true).Count); // ExSkip
}

/// <summary>
/// Creates a new table in the document with the given dimensions and text in each cell.
/// </summary>
private Table CreateTable(Document doc, int rowCount, int cellCount, string cellText)
{
    Table table = new Table(doc);

    // Create the specified number of rows.
    for (int rowId = 1; rowId <= rowCount; rowId++)
    {
        Row row = new Row(doc);
        table.AppendChild(row);

        // Create the specified number of cells for each row.
        for (int cellId = 1; cellId <= cellCount; cellId++)
        {
            Cell cell = new Cell(doc);
            row.AppendChild(cell);
            // Add a blank paragraph to the cell.
            cell.AppendChild(new Paragraph(doc));

            // Add the text.
            cell.FirstParagraph.AppendChild(new Run(doc, cellText));
        }
    }

    return table;
}
[Visual Basic]

<Test> _
Public Sub NestedTablesUsingNodeConstructors()
    Dim doc As New Document()

    ' Create the outer table with three rows and four columns.
    Dim outerTable As Table = CreateTable(doc, 3, 4, "Outer Table")
    ' Add it to the document body.
    doc.FirstSection.Body.AppendChild(outerTable)

    ' Create another table with two rows and two columns.
    Dim innerTable As Table = CreateTable(doc, 2, 2, "Inner Table")
    ' Add this table to the first cell of the outer table.
    outerTable.FirstRow.FirstCell.AppendChild(innerTable)

    doc.Save(MyDir & "Table.CreateNestedTable Out.doc")

    Assert.AreEqual(2, doc.GetChildNodes(NodeType.Table, True).Count) ' ExSkip
End Sub

''' <summary>
''' Creates a new table in the document with the given dimensions and text in each cell.
''' </summary>
Private Function CreateTable(ByVal doc As Document, ByVal rowCount As Integer, ByVal cellCount As Integer, ByVal cellText As String) As Table
    Dim table As New Table(doc)

    ' Create the specified number of rows.
    For rowId As Integer = 1 To rowCount
        Dim row As New Row(doc)
        table.AppendChild(row)

        ' Create the specified number of cells for each row.
        For cellId As Integer = 1 To cellCount
            Dim cell As New Cell(doc)
            row.AppendChild(cell)
            ' Add a blank paragraph to the cell.
            cell.AppendChild(New Paragraph(doc))

            ' Add the text.
            cell.FirstParagraph.AppendChild(New Run(doc, cellText))
        Next cellId
    Next rowId

    Return table
End Function
Examples
Shows how to insert a table using the constructors of nodes.
[C#]

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.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, 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.RowFormat.AllowBreakAcrossPages = true;
table.AppendChild(row);

// We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths);

// Create a cell and add it to the row
Cell cell = new Cell(doc);
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue;
cell.CellFormat.Width = 80;

// Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(new Paragraph(doc));
cell.FirstParagraph.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.Clone(false));
row.LastCell.AppendChild(new Paragraph(doc));
row.LastCell.FirstParagraph.AppendChild(new Run(doc, "Row 1, Cell 2 Text"));

doc.Save(MyDir + "Table.InsertTableUsingNodes Out.doc");
[Visual Basic]

Dim doc As 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.
Dim table As New Table(doc)
' Add the table to the document.
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, 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.
Dim row As New Row(doc)
row.RowFormat.AllowBreakAcrossPages = True
table.AppendChild(row)

' We can now apply any auto fit settings.
table.AutoFit(AutoFitBehavior.FixedColumnWidths)

' Create a cell and add it to the row
Dim cell As New Cell(doc)
cell.CellFormat.Shading.BackgroundPatternColor = Color.LightBlue
cell.CellFormat.Width = 80

' Add a paragraph to the cell as well as a new run with some text.
cell.AppendChild(New Paragraph(doc))
cell.FirstParagraph.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.Clone(False))
row.LastCell.AppendChild(New Paragraph(doc))
row.LastCell.FirstParagraph.AppendChild(New Run(doc, "Row 1, Cell 2 Text"))

doc.Save(MyDir & "Table.InsertTableUsingNodes Out.doc")
See Also