Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Unable to add tables in any location other than end of document #1204

@jonnyzwi

Description

@jonnyzwi

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

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions