Skip to content

Insert table after specific text found in Word document using python-docx #1298

@Mishidesh

Description

@Mishidesh

I see the document of python-docx for handling Word files in python. For the tutorial, I can use the add_table to create the table in the last line.

I want to add the tables with the subheading when I detect the specific word found in the Word file. This code is not adding tables after the text found.All table that i've tried to add are systematically inserted in the bottom of my document, and i don't want it. How` do I modify my code:

`for i in range(tableCount):
df = data_frames[f'df_{i}'].reset_index(drop=True) # Reset the index
df = df.drop(columns=['Unnamed: 0'])
headers = df.columns.tolist()
data = df.values.tolist()
text_search = "A list is find here"
sub_heading = "2.5." + str(i)
document = Document('./my_document.docx')

for p in document.paragraphs:
    if text_search in paragraph.text:
        ##  Create the heading in here
        heading = document.add_heading(sub_heading,level=2)
        ##  Create the table in here
        table = document.add_table(rows=len(data)+1, cols=len(headers))`

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