Skip to content

Tables with incomplete columns are not parsed correctly #1193

Closed

Description

@tuv-jens-rutenkroeger

docx_table_bug.zip

If a table contains an additional column in the second row, the cells are not assigned correctly:

Please see the attached code example.

Used classes:

docx.table.Table
docx.oxml.table.CT_Tbl

Example:

Input word table:

A1	B1	C1
A2	B2	C2	D2

Output:

A1	B1	C1   A2
B2	C2	D2

Activity

  1. tuv-jens-rutenkroeger commented on Mar 23, 2023

    @tuv-jens-rutenkroeger
    Author

    The issue is caused by the fact that the class Table operates on a list of cells and uses arithmetic to calculate the element's index.
    That approach only works for tables with the same number of columns in each row.
    -->

    def cell(self, row_idx, col_idx):

  2. scanny commented on May 1, 2024

    @scanny
    Contributor

    This is fixed in the latest release v1.1.2 which enhanced aspects of Table support to accommodate rows with unequal numbers of cells.

    Depending on what you're doing, the following approach may suit:

    >>> for row in table.rows:
    ...    print(row.cells)
    ("A1", "B1", "C1")
    ("A2", "B2", "C2", "D2")

    Note this does not tell the whole story because the same output would be produced by a table like this:

    	A1	B1	C1
    A2	B2	C2	D2
    

    To maintain column integrity you will need an approach like this:

    def iter_row_cell_texts(row: _Row) -> Iterator[str]:
        for _ in range(row.grid_cols_before):
            yield ""
        for cell in row.cells:
            yield cell.text
        for _ in range(row.grid_cols_after):
            yield ""
    
    >>> for row in table.rows:
    ...    print(tuple(iter_row_cell_texts(row))
    ("",   "A1", "B1", "C1")
    ("A2", "B2", "C2", "D2")

    This new page in the docs is probably worth a read: https://python-docx.readthedocs.io/en/latest/user/tables.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions