bkcollection
bkcollection

Reputation: 924

Python to mailmerge csv to word in continuous in one document

I want to mailmerge a table in csv(List.csv) to word(example1.docx) but continuously into multiple pages in one word document. The function is something like "Next Record" in MS Word. I have a template (Test.docx). I can't find in Python.

from __future__ import print_function
import pandas as pd
from mailmerge import MailMerge
from datetime import date

# Define the templates - assumes they are in the same directory as the code
template_1 = "Test.docx"
df1 = pd.read_csv('List.csv')
looprange = range(int(len(df1.index)))

for j in looprange:
    document_1 = MailMerge(template_1)
    document_1.merge(
        BusinessName=df1.BusinessName[j],
        Name= df1.Name[j],
       )
document_1.write('example1.docx')

List.csv

enter image description here

Test.docx

enter image description here

However, I only get the output of the last input and is only one page and it is repeated data. Desired output suppose to be suppose to be all 4 row data in two pages. The data should be different left and right as I split the template to two column.

Output currently:

enter image description here

Upvotes: 0

Views: 84

Answers (1)

dofften
dofften

Reputation: 9

Using the merge_rows function of mailmerge worked for me when using data from excel sheets. In the following example I create a list of dictionaries with the data from the sheet, then add it to the template using merge_rows. Here is a code snippet that I think would work for your use case.

import pandas as pd
from mailmerge import MailMerge

# Define the templates - assumes they are in the same directory as the code
template = "Test.docx"
df1 = pd.read_csv('List.csv')

document = MailMerge(template)

#To make sure your fields are correct
print(document.get_merge_fields())

# Prepare rows for merging data
table_rows = []
for _, row in df1.iterrows():
    table_rows.append({
        "Name": row["Name"],
        "BusinessName": row["BusinessName"],
    })

# Merge all data into the template
document.merge_rows("Name", table_rows)
# Save the output Word document
document.write('output.docx')

Upvotes: -1

Related Questions