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

Namespace: Aspose.Words.Tables
Assembly: Aspose.Words (in Aspose.Words.dll) Version: 19.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 exampleAbsoluteHorizontalDistance
Gets absolute horizontal floating table position specified by the table properties, in points. Default value is 0.
Public propertyCode exampleAbsoluteVerticalDistance
Gets absolute vertical floating table position specified by the table properties, in points. Default value is 0.
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 propertyCode exampleAllowCellSpacing
Gets or sets the "Allow spacing between cells" option.
Public propertyCode exampleAllowOverlap
Gets whether a floating table shall allow other floating objects in the document to overlap its extents when displayed. Default value is true.
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 propertyCode exampleCount
Gets the number of immediate children of this node.
(Inherited from CompositeNode.)
Public propertyCode exampleDescription
Gets or sets description of this table. It provides an alternative text representation of the information contained in the table.
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 exampleHorizontalAnchor
Gets the base object from which the horizontal positioning of floating table should be calculated. Default value is Column.
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 exampleRelativeHorizontalAlignment
Gets floating table relative horizontal alignment.
Public propertyCode exampleRelativeVerticalAlignment
Gets floating table relative vertical alignment.
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
Gets or sets TextWrapping for table.
Public propertyCode exampleTitle
Gets or sets title of this table. It provides an alternative text representation of the information contained in the table.
Public propertyCode exampleTopPadding
Gets or sets the amount of space (in points) to add above the contents of cells.
Public propertyCode exampleVerticalAnchor
Gets the base object from which the vertical positioning of floating table should be calculated. Default value is Margin.
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 (Inherited from Node.)
Public methodCode exampleConvertToHorizontallyMergedCells
Converts cells horizontally merged by width to cells merged by HorizontalMerge.
Protected methodCoreRemoveSelfOnly (Inherited from CompositeNode.)
Public methodCode exampleCreateNavigator
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
Returns a live 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 methodCode exampleInsertBefore
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.)
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(ArtifactsDir + "Table.ClearBorders.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(ArtifactsDir + "Table.CombineTables.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();
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.OfType<Table>())
{
    // 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.OfType<Row>())
    {
        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.OfType<Cell>())
        {
            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("\tEnd of Row {0}", rowIndex);
    }

    Console.WriteLine("End of Table {0}", tableIndex);
    Console.WriteLine();
}
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 algorithm 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"));

// Remove spacing between cells
table.AllowCellSpacing = false;

doc.Save(ArtifactsDir + "Table.InsertTableUsingNodes.doc");
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(ArtifactsDir + "Table.CreateNestedTable.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));
        }
    }

    // You can add title and description to your table only when added at least one row to the table first
    // This properties are meaningful for ISO / IEC 29500 compliant DOCX documents(see the OoxmlCompliance class)
    // When saved to pre-ISO/IEC 29500 formats, the properties are ignored
    table.Title = "Aspose table title";
    table.Description = "Aspose table description";

    return table;
}
See Also