This functions returns the paragraphs and tables of a document or part of a document (you can have paragraphs and tables inside tables):
def iter_block_items(parent):
# https://github.com/python-openxml/python-docx/issues/40
from docx.document import Document
from docx.oxml.table import CT_Tbl
from docx.oxml.text.paragraph import CT_P
from docx.table import _Cell, Table
from docx.text.paragraph import Paragraph
"""
Yield 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
else:
raise ValueError("something's not right")
# print('parent_elm: '+str(type(parent_elm)))
for child in parent_elm.iterchildren():
if isinstance(child, CT_P):
yield Paragraph(child, parent)
elif isinstance(child, CT_Tbl):
yield Table(child, parent) # No recursion, return tables as tables
# table = Table(child, parent) # Use recursion to return tables as paragraphs
# for row in table.rows:
# for cell in row.cells:
# yield from iter_block_items(cell)
Now, to use it, construct your dictionary where it says Do some logic here
:
document = Document(filepath)
for iter_block_item in iter_block_items(document): # Iterate over paragraphs and tables
# print('iter_block_item type: '+str(type(iter_block_item)))
if isinstance(iter_block_item, Paragraph):
paragraph = iter_block_item # Do some logic here
else:
table = iter_block_item # Do some logic here
Note: @Elayaraja Dev answer cannot be edited, this answer has the current form of iter_block_items (since docx internals were updated)