Search code examples
pythonpython-docx

Detect table within table in python-docx


When using python-docx Table objects, is there a way to distinguish between a table that is within a cell of another table, to a plain "independent" table?


Solution

  • There is no property on a docx.table.Table object that will tell you whether it is nested within another table, but you can find tables that are in other tables like this:

    def iter_tables_within_table(table):
        for row in table.rows:
            for cell in row.cells:
                for nested_table in cell.tables:
                    yield nested_table
                    yield from iter_tables_with_table(nested_table)
    
    for nested_table in iter_tables_with_table(table):
        print("found a nested table %s" % nested_table)