Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 990
Vignesh Avatar asked Nov 17 '25 14:11

Vignesh


1 Answers

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)
like image 160
scanny Avatar answered Nov 19 '25 02:11

scanny



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!