python-docx get tables from paragraph

Konstantyn picture Konstantyn · Mar 24, 2015 · Viewed 10k times · Source

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 ?

Answer

Elayaraja Dev picture Elayaraja Dev · Sep 14, 2017
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))