[Python] Using `python-docx`, extract all tables from a specific section of a Word Document

Discussão em 'Python' iniciado por Stack, Maio 19, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following Word File (test_doc.docx) containing multiple sections and tables. I am only interested in capturing tables from Section 2 — Here's a markdown representation of it:

    Section 1

    Column A Column B
    Cell 1 Cell 2
    Cell 3 Cell 4
    Section 2

    A B C D E
    Not Lorem ipsum Not Lorem ipsum Not Lorem Ipsum Not empty Not Lorem Ipsum
    A B C D E
    Some text Some text Some text Some text Some text
    Section 3


    Another table, but not interested by this one.

    A Column B
    Cell 1 Cell 2
    Cell 3 Cell 4

    Using python-docx, we can easily iter through all tables and store them in a list.

    However, I can't seem to find any way to specify that I only want a subset of tables from a specific section. (such as Section 2)

    from docx import Document

    crash_test_doc = Document("test_doc.docx")

    tables = list()

    for table in crash_test_doc.tables:
    tables.append(table)

    len(tables) # = 4 -> matches all the tables from the document

    Continue reading...

Compartilhe esta Página