Skip to content

Instantly share code, notes, and snippets.

@timbledum
Last active October 16, 2018 17:11
Show Gist options
  • Save timbledum/3258e1121a06dc367c00721f03fc9be7 to your computer and use it in GitHub Desktop.
Save timbledum/3258e1121a06dc367c00721f03fc9be7 to your computer and use it in GitHub Desktop.
# coding: utf-8
"""
A module to generate ############### forms given
a template and a spreadsheet.
This script:
1. Connects to a spreadsheet
2. Populates a dictionary with information from the spreadsheet/the entity
3. Populates template files with the information above
"""
import sys
import os
import petl
from mailmerge import MailMerge
import easygui
TEMPLATE = "template.docx"
INPUT_FILE_NAME = "input_file_name.xlsx"
OUTPUT_FILE = "output_file {}.docx"
OUTPUT_FOLDER = "output"
#############
# Functions #
#############
def write_data(merge_data, template, output_file, output_folder):
"""Populate a word template with the provided dict into an output folder"""
try:
document = MailMerge(template)
except FileNotFoundError:
easygui.msgbox(
"Template file not found! Please locate '{}'".format(template)
+ " and place it in the directory with this file."
)
sys.exit(0)
# ensure all fields have data
data = {key: "" for key in document.get_merge_fields()}
data.update(merge_data)
try:
os.makedirs(output_folder, exist_ok=True)
document.merge(**merge_data)
document.write(
os.path.join(output_folder, output_file.format(merge_data["index"]))
)
except BaseException:
easygui.exceptionbox()
sys.exit(0)
##########
# Script #
##########
if __name__ == "__main__":
table = petl.fromxlsx(INPUT_FILE_NAME, row_offset=4)
for merge_data in table.dicts():
write_data(merge_data, TEMPLATE, OUTPUT_FILE, OUTPUT_FOLDER)
easygui.msgbox("Done!")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment