python-docx get tables from paragraph
Asked Answered
L

4

8

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 ?

Libb answered 24/3, 2015 at 18:57 Comment(0)
C
8
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))
Chasechaser answered 14/9, 2017 at 9:38 Comment(5)
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.Ilion
May you know, if it is possible to refactor this function and also find InlineShapes ?Oppidan
I want to direct future readers to this github on the issue as this is a requested feature for the APIHillary
@ImaneE. probably too late but your issue maybe related to this changeHillary
You left out _Row. It should be from docx.table import _Cell, Table, _RowHeadless
U
4

Not sure if i am helping but here's my way of doing

def printTables(doc):
    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                for paragraph in cell.paragraphs:
                    print(paragraph.text)
                printTables(cell)
Unwilling answered 29/1, 2020 at 6:24 Comment(2)
Unfortunately it prints table header.Libb
Suggestion: You can try printing the paragraph text into a list and remove the first element which is most likely going to be the table header? Do share if you can get it up and running!Unwilling
H
3

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)

Hatcher answered 5/4, 2022 at 14:43 Comment(0)
L
1

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.

Lynden answered 11/8, 2015 at 23:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.