0

I'm reading values from an excel file and putting them into placeholders on the word doc template. Each template is for one row. Trying to combine multiple word docs into one with python. Each individual doc has the picture showing. Once they are combined, I'm getting the "picture can't be displayed" error. This is the code

from openpyxl import load_workbook
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Cm
import os
from docx import Document
from docx.enum.text import WD_BREAK

# Define the file paths
excel_file_path = "/Users/muhammad/Documents/namelist.xlsx"
word_doc_path = "/Users/muhammad/Documents/template.docx"
image_path = "/Users/muhammad/Documents/a2a.png"
output_dir = "/Users/muhammad/Documents/output"
combined_output_path = "/Users/muhammad/Documents/combined_output.docx"

# Load the Excel workbook and select the appropriate sheet
workbook = load_workbook(excel_file_path)
sheet = workbook.active  # Assuming the data is in the active sheet

# Create a new combined document
combined_doc = Document()

# Iterate through the rows in the Excel file
for row in sheet.iter_rows(min_row=2, values_only=True):
    sn, oid, intent, name = row

    # Load the Word template document
    template = DocxTemplate(word_doc_path)

    # Declare template variables
    context = {
        'SN': f'S/N {sn}',
        'OID': f'OID {oid}',
        'INTENT': f'({intent})',
        'NAME': name
    }

   

    # Render automated doc
    template.render(context)

    # Generate the output file path
    output_file_path = os.path.join(output_dir, f"output_{sn}.docx")

    # Save the Word document for the current row
    template.save(output_file_path)

    # Open the individual output document
    output_doc = Document(output_file_path)

    # Append the content of the individual output document to the combined document
    for element in output_doc._body._body:
        combined_doc._body._body.append(element)

    

# Save the combined output document
combined_doc.save(combined_output_path)

combined doc Individual doc

I've tried messing around with settings on Word but haven't had success. Seems that the issue is with the appending. I've tried different methods of combining the docs, but nothing works as well as the above code for formatting

0 Answers0