-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Closed
Description
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')
Metadata
Metadata
Assignees
Labels
No labels