python-docx get tables from paragraph

13,216

Solution 1

from docx import Document
from docx.document import Document as _Document
from docx.oxml.text.paragraph import CT_P
from docx.oxml.table import CT_Tbl
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
def iter_block_items(parent):
"""
Generate a reference to each paragraph and table child within *parent*,
in document order. Each returned value is an instance of either Table or
Paragraph. *parent* would most commonly be a reference to a main
Document object, but also works for a _Cell object, which itself can
contain paragraphs and tables.
"""
if isinstance(parent, _Document):
    parent_elm = parent.element.body
elif isinstance(parent, _Cell):
    parent_elm = parent._tc
elif isinstance(parent, _Row):
    parent_elm = parent._tr
else:
    raise ValueError("something's not right")
for child in parent_elm.iterchildren():
    if isinstance(child, CT_P):
        yield Paragraph(child, parent)
    elif isinstance(child, CT_Tbl):
        yield Table(child, parent)
document = Document('test.docx')
for block in iter_block_items(document):

#print(block.text if isinstance(block, Paragraph) else '<table>')
if isinstance(block, Paragraph):
    print(block.text)
elif isinstance(block, Table):
    for row in block.rows:
        row_data = []
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                row_data.append(paragraph.text)
        print("\t".join(row_data))

Solution 2

There is no such method implemented(yet) on the python-docx library but there is a workaround to iterate through all elements of the docx in the order they are presented: https://github.com/python-openxml/python-docx/issues/40

You can try iterating through all these and check if the object is an instance of a table or paragraph and base your logic on that.

Share:
13,216
Konstantyn
Author by

Konstantyn

Updated on July 11, 2022

Comments

  • Konstantyn
    Konstantyn almost 2 years

    I have .docx file with many paragraphs and tables like:

    1. par1
      • table1
      • table2
      • table3
    2. par2

      • table1
      • table2

      2.1 par21

      • table1
      • table2

    I need to iterate all objects and make dictionary, maybe in json format like:

       {par1: [table1, table2, table3], par2[table1,table2, {par21: [table1,table2]} ] }
    
        from docx.api import Document
    
        filename = 'test.docx'
        document = Document(docx=filename)
        for table in document.tables:
            print table
    
        for paragraph in document.paragraphs:
            print paragraph.text
    

    How can I relate each paragraph and tables?

    Can you suggest something ?

  • Imane E.
    Imane E. over 6 years
    I tried this, not all text is showing, only column names appear, is this what it's supposed to render? is this that docx don't open correctly on my system? I would like to learn more about this code and how can I fix my problem.
  • o.O
    o.O over 5 years
    May you know, if it is possible to refactor this function and also find InlineShapes ?
  • Czarking
    Czarking over 3 years
    I want to direct future readers to this github on the issue as this is a requested feature for the API
  • Czarking
    Czarking over 3 years
    @ImaneE. probably too late but your issue maybe related to this change
  • Cazforshort
    Cazforshort over 2 years
    You left out _Row. It should be from docx.table import _Cell, Table, _Row