Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
jonnyzwi opened this issue Apr 11, 2023 · 1 comment
Closed

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

jonnyzwi opened this issue Apr 11, 2023 · 1 comment

Comments

@jonnyzwi
Copy link

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')
@scanny
Copy link
Contributor

scanny commented Sep 24, 2023

Closing as stale/inactive.

@scanny scanny closed this as completed Sep 24, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants