You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Unable to add tables in any location other than end of document #1204
I have a Word docx with {{TABLE_PLACEHOLDER}} written in the text of the doc.
I would like to add a table in that location, but cannot manage to add a table anywhere else but at the end of the document.
Any help is appreciated.
import pandas as pd
from docx import Document
doc = Document('template_document.docx')
df = pd.DataFrame({
'Column 1': [1, 2, 3],
'Column 2': [4, 5, 6],
'Column 3': [7, 8, 9]
})
table_data = df.values.tolist()
for p in doc.paragraphs:
if '{{TABLE_PLACEHOLDER}}' in p.text:
p.insert_paragraph_before() ### THIS APPEARS TO DO NOTHING
table = doc.add_table(rows=len(table_data)+1, cols=len(df.columns))
for i, row in enumerate(table_data):
for j, val in enumerate(row):
cell = table.cell(i+1, j)
cell.text = str(val)
for j, header in enumerate(df.columns):
cell = table.cell(0, j)
cell.text = header
doc.save('output_document.docx')
Activity
scanny commentedon Sep 24, 2023
Closing as stale/inactive.