[Python] How do I replace text in a word document table using information from an excel file?

Discussão em 'Python' iniciado por Stack, Dezembro 17, 2024.

  1. Stack

    Stack Membro Participativo

    I have a template where I am trying to replace certain text with information from excel. The problem is that once I have replaced and saved the file, the conditions I have set no longer apply and all files are saved with the same information from the same excel row.

    I also tried duplicating the word file with docx but the format was all jumbled up.

    I run a loop on the function below, but every single word document table has all the same information from the same row.

    Here is my code:

    from docx import Document
    import pandas as pd


    def replace_and_save(excel_file, word_file, output_file):
    df = pd.read_excel(excel_file)

    doc = Document(word_file)
    table = doc.tables[0]

    for row_index, excel_row in df.iterrows():
    name = excel_row[2]
    sex = excel_row[3]
    nationality = excel_row[4]
    passport_num = excel_row[6]

    #This gives different information for each row
    print(name, sex, nationality, passport_num)

    for row in table.rows:
    for cell in row.cells:
    for paragraph in cell.paragraphs:
    for run in paragraph.runs:
    if "<Name>" in run.text:
    run.text = run.text.replace("<Name>", name)
    if "<Passport>" in run.text:
    run.text = run.text.replace("<Passport>", passport_num)
    if "<Nationality>" in run.text:
    run.text = run.text.replace("<Nationality>", nationality)
    if "<Sex>" in run.text:
    run.text = run.text.replace("<Sex>", sex)

    doc.save(output_file)

    Continue reading...

Compartilhe esta Página