Search code examples
pythonpython-docx

Python docx: Inserting paragraph after a table


If we have a saved docx with a table on it and we want to insert a paragraph after the table, how do we do that?

I understand that Tables can be easily found with

for table in document.tables:
    ...

python-docx: Inserting a paragraph before a table has solution for inserting a paragraph before a table. How could one implement a similar solution for inserting a paragraph after a table.

Unfortunately, the inner workings of the python-docx is complicate for me to understand being fairly new to programming.

Any help on this is much appreciated.


Solution

  • This should do the trick in your case:

    from docx.text.paragraph import Paragraph
    
    def table_insert_paragraph_after(table):
        """Return new `Paragraph` object inserted directly after `table`.
    
        `table` must already be immediately followed by a paragraph. So
        This won't work for a table followed by another table or a table
        at the end of the document.
        """
        p = table._tbl.getnext()
        paragraph = Paragraph(p, table._parent)
        return paragraph.insert_paragraph_before()
    
    paragraph = table_insert_paragraph_after(table)