Table class

Table class

Represents a table in a Word document. To learn more, visit the Working with Tables documentation article.

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.

Inheritance: TableCompositeNodeNode

Constructors

NameDescription
Table(doc)Initializes a new instance of the Table class.

Properties

NameDescription
absolute_horizontal_distanceGets or sets absolute horizontal floating table position specified by the table properties, in points. Default value is 0.
absolute_vertical_distanceGets or sets absolute vertical floating table position specified by the table properties, in points. Default value is 0.
alignmentSpecifies how an inline table is aligned in the document.
allow_auto_fitAllows Microsoft Word and Aspose.Words to automatically resize cells in a table to fit their contents.
allow_cell_spacingGets or sets the “Allow spacing between cells” option.
allow_overlapGets whether a floating table shall allow other floating objects in the document to overlap its extents when displayed. Default value is True.
bidiGets or sets whether this is a right-to-left table.
bottom_paddingGets or sets the amount of space (in points) to add below the contents of cells.
cell_spacingGets or sets the amount of space (in points) between the cells.
countGets the number of immediate children of this node.
(Inherited from CompositeNode)
custom_node_idSpecifies custom node identifier.
(Inherited from Node)
descriptionGets or sets description of this table. It provides an alternative text representation of the information contained in the table.
distance_bottomGets or sets distance between table bottom and the surrounding text, in points.
distance_leftGets or sets distance between table left and the surrounding text, in points.
distance_rightGets or sets distance between table right and the surrounding text, in points.
distance_topGets or sets distance between table top and the surrounding text, in points.
documentGets the document to which this node belongs.
(Inherited from Node)
first_childGets the first child of the node.
(Inherited from CompositeNode)
first_rowReturns the first Row node in the table.
has_child_nodesReturns True if this node has any child nodes.
(Inherited from CompositeNode)
horizontal_anchorGets the base object from which the horizontal positioning of floating table should be calculated. Default value is RelativeHorizontalPosition.COLUMN.
is_compositeReturns True if this node can contain other nodes.
(Inherited from Node)
last_childGets the last child of the node.
(Inherited from CompositeNode)
last_rowReturns the last Row node in the table.
left_indentGets or sets the value that represents the left indent of the table.
left_paddingGets or sets the amount of space (in points) to add to the left of the contents of cells.
next_siblingGets the node immediately following this node.
(Inherited from Node)
node_typeReturns NodeType.TABLE.
parent_nodeGets the immediate parent of this node.
(Inherited from Node)
preferred_widthGets or sets the table preferred width.
previous_siblingGets the node immediately preceding this node.
(Inherited from Node)
rangeReturns a Range object that represents the portion of a document that is contained in this node.
(Inherited from Node)
relative_horizontal_alignmentGets or sets floating table relative horizontal alignment.
relative_vertical_alignmentGets or sets floating table relative vertical alignment.
right_paddingGets or sets the amount of space (in points) to add to the right of the contents of cells.
rowsProvides typed access to the rows of the table.
styleGets or sets the table style applied to this table.
style_identifierGets or sets the locale independent style identifier of the table style applied to this table.
style_nameGets or sets the name of the table style applied to this table.
style_optionsGets or sets bit flags that specify how a table style is applied to this table.
text_wrappingGets or sets Table.text_wrapping for table.
titleGets or sets title of this table. It provides an alternative text representation of the information contained in the table.
top_paddingGets or sets the amount of space (in points) to add above the contents of cells.
vertical_anchorGets the base object from which the vertical positioning of floating table should be calculated. Default value is RelativeVerticalPosition.MARGIN.

Methods

NameDescription
accept(visitor)Accepts a visitor.
accept_end(visitor)Accepts a visitor for visiting the end of the table.
accept_start(visitor)Accepts a visitor for visiting the start of the table.
append_child(new_child)Adds the specified node to the end of the list of child nodes for this node.
(Inherited from CompositeNode)
auto_fit(behavior)Resizes the table and cells according to the specified auto fit behavior.
clear_borders()Removes all table and cell borders on this table.
clear_shading()Removes all shading on the table.
clone(is_clone_children)Creates a duplicate of the node.
(Inherited from Node)
convert_to_horizontally_merged_cells()Converts cells horizontally merged by width to cells merged by CellFormat.horizontal_merge.
ensure_minimum()If the table has no rows, creates and appends one Row.
get_ancestor(ancestor_type)Gets the first ancestor of the specified object type.
(Inherited from Node)
get_ancestor(ancestor_type)Gets the first ancestor of the specified NodeType.
(Inherited from Node)
get_child(node_type, index, is_deep)Returns an Nth child node that matches the specified type.
(Inherited from CompositeNode)
get_child_nodes(node_type, is_deep)Returns a live collection of child nodes that match the specified type.
(Inherited from CompositeNode)
get_text()Gets the text of this node and of all its children.
(Inherited from Node)
index_of(child)Returns the index of the specified child node in the child node array.
(Inherited from CompositeNode)
insert_after(new_child, ref_child)Inserts the specified node immediately after the specified reference node.
(Inherited from CompositeNode)
insert_before(new_child, ref_child)Inserts the specified node immediately before the specified reference node.
(Inherited from CompositeNode)
next_pre_order(root_node)Gets next node according to the pre-order tree traversal algorithm.
(Inherited from Node)
node_type_to_string(node_type)A utility method that converts a node type enum value into a user friendly string.
(Inherited from Node)
prepend_child(new_child)Adds the specified node to the beginning of the list of child nodes for this node.
(Inherited from CompositeNode)
previous_pre_order(root_node)Gets the previous node according to the pre-order tree traversal algorithm.
(Inherited from Node)
remove()Removes itself from the parent.
(Inherited from Node)
remove_all_children()Removes all the child nodes of the current node.
(Inherited from CompositeNode)
remove_child(old_child)Removes the specified child node.
(Inherited from CompositeNode)
remove_smart_tags()Removes all SmartTag descendant nodes of the current node.
(Inherited from CompositeNode)
select_nodes(xpath)Selects a list of nodes matching the XPath expression.
(Inherited from CompositeNode)
select_single_node(xpath)Selects the first Node that matches the XPath expression.
(Inherited from CompositeNode)
set_border(border_type, line_style, line_width, color, is_override_cell_borders)Sets the specified table border to the specified line style, width and color.
set_borders(line_style, line_width, color)Sets all table borders to the specified line style, width and color.
set_shading(texture, foreground_color, background_color)Sets shading to the specified values on whole table.
to_string(save_format)Exports the content of the node into a string in the specified format.
(Inherited from Node)
to_string(save_options)Exports the content of the node into a string using the specified save options.
(Inherited from Node)

Examples

Shows how to build a formatted 2x2 table.

doc = aw.Document()
builder = aw.DocumentBuilder(doc=doc)
table = builder.start_table()
builder.insert_cell()
builder.cell_format.vertical_alignment = aw.tables.CellVerticalAlignment.CENTER
builder.write('Row 1, cell 1.')
builder.insert_cell()
builder.write('Row 1, cell 2.')
builder.end_row()
# While building the table, the document builder will apply its current RowFormat/CellFormat property values
# to the current row/cell that its cursor is in and any new rows/cells as it creates them.
self.assertEqual(aw.tables.CellVerticalAlignment.CENTER, table.rows[0].cells[0].cell_format.vertical_alignment)
self.assertEqual(aw.tables.CellVerticalAlignment.CENTER, table.rows[0].cells[1].cell_format.vertical_alignment)
builder.insert_cell()
builder.row_format.height = 100
builder.row_format.height_rule = aw.HeightRule.EXACTLY
builder.cell_format.orientation = aw.TextOrientation.UPWARD
builder.write('Row 2, cell 1.')
builder.insert_cell()
builder.cell_format.orientation = aw.TextOrientation.DOWNWARD
builder.write('Row 2, cell 2.')
builder.end_row()
builder.end_table()
# Previously added rows and cells are not retroactively affected by changes to the builder's formatting.
self.assertEqual(0, table.rows[0].row_format.height)
self.assertEqual(aw.HeightRule.AUTO, table.rows[0].row_format.height_rule)
self.assertEqual(100, table.rows[1].row_format.height)
self.assertEqual(aw.HeightRule.EXACTLY, table.rows[1].row_format.height_rule)
self.assertEqual(aw.TextOrientation.UPWARD, table.rows[1].cells[0].cell_format.orientation)
self.assertEqual(aw.TextOrientation.DOWNWARD, table.rows[1].cells[1].cell_format.orientation)
doc.save(file_name=ARTIFACTS_DIR + 'DocumentBuilder.BuildTable.docx')

Shows how to create a table.

doc = aw.Document()
table = aw.tables.Table(doc)
doc.first_section.body.append_child(table)
# Tables contain rows, which contain cells, which may have paragraphs
# with typical elements such as runs, shapes, and even other tables.
# Calling the "EnsureMinimum" method on a table will ensure that
# the table has at least one row, cell, and paragraph.
first_row = aw.tables.Row(doc)
table.append_child(first_row)
first_cell = aw.tables.Cell(doc)
first_row.append_child(first_cell)
paragraph = aw.Paragraph(doc)
first_cell.append_child(paragraph)
# Add text to the first cell in the first row of the table.
run = aw.Run(doc=doc, text='Hello world!')
paragraph.append_child(run)
doc.save(file_name=ARTIFACTS_DIR + 'Table.CreateTable.docx')

Shows how to iterate through all tables in the document and print the contents of each cell.

doc = aw.Document(file_name=MY_DIR + 'Tables.docx')
tables = doc.first_section.body.tables
self.assertEqual(2, len(list(tables)))
i = 0
while i < tables.count:
    print(f'Start of Table {i}')
    rows = tables[i].rows
    # We can use the "ToArray" method on a row collection to clone it into an array.
    self.assertSequenceEqual(list(rows), list(rows))
    self.assertNotEqual(rows, list(rows))
    j = 0
    while j < rows.count:
        print(f'\tStart of Row {j}')
        cells = rows[j].cells
        # We can use the "ToArray" method on a cell collection to clone it into an array.
        self.assertSequenceEqual(list(cells), list(cells))
        self.assertNotEqual(cells, list(cells))
        k = 0
        while k < cells.count:
            cell_text = cells[k].to_string(save_format=aw.SaveFormat.TEXT).strip()
            print(f'\t\tContents of Cell:{k} = "{cell_text}"')
            k += 1
        print(f'\tEnd of Row {j}')
        j += 1
    print(f'End of Table {i}\n')
    i += 1

Shows how to build a nested table without using a document builder.

def create_nested_table():
    doc = aw.Document()
    # Create the outer table with three rows and four columns, and then add it to the document.
    outer_table = create_table(doc, 3, 4, 'Outer Table')
    doc.first_section.body.append_child(outer_table)
    # Create another table with two rows and two columns and then insert it into the first table's first cell.
    inner_table = create_table(doc, 2, 2, 'Inner Table')
    outer_table.first_row.first_cell.append_child(inner_table)
    doc.save(ARTIFACTS_DIR + 'Table.create_nested_table.docx')

def create_table(doc: aw.Document, row_count: int, cell_count: int, cell_text: str) -> aw.tables.Table:
    """Creates a new table in the document with the given dimensions and text in each cell."""
    table = aw.tables.Table(doc)
    for row_id in range(1, row_count + 1):
        row = aw.tables.Row(doc)
        table.append_child(row)
        for cell_id in range(1, cell_count + 1):
            cell = aw.tables.Cell(doc)
            cell.append_child(aw.Paragraph(doc))
            cell.first_paragraph.append_child(aw.Run(doc, cell_text))
            row.append_child(cell)
    # You can use the "title" and "description" properties to add a title and description respectively to your table.
    # The table must have at least one row before we can use these properties.
    # These properties are meaningful for ISO / IEC 29500 compliant .docx documents (see the OoxmlCompliance class).
    # If we save the document to pre-ISO/IEC 29500 formats, Microsoft Word ignores these properties.
    table.title = 'Aspose table title'
    table.description = 'Aspose table description'
    return table

See Also