I am using the python-docx library to modify an existing docx file. I want to add a table to the fifth line of the document. the issue is that when I use document.add_table( ), the table is added at the END of the document. I want to be able to choose WHERE to add the table in the document. Is there any way to do this? I wasn't able to find anything that worked online.
I Tried this :
from docx import Documentdoc = Document('existing_document')table_data = [ ['Column 1', 'Column 2'], ['Data 1', 'Data 2'], ['Data 3', 'Data 4']]table = doc.add_table(rows=1,cols=2)for i, row_data in enumerate(table_data): row = table.rows[i] for j, cell_data in enumerate(row_data): row.cells[j].text = cell_datadoc.save('modified_document.docx')When I do this, the table is added to the end of the document.
I tried using insert_paragraph_before( ):
table = doc.add_table(rows=1,cols=2)doc.paragraphs[5].insert_paragraph_before(table)However, this triggered an error, as insert_paragraph_before seems to only works with strings.