Create personalized Word documents with data from Central

Here's a Python script that uses mail merge to create personalized Word documents with data from Central. This script is great if you want to personalized reports (e.g., a site report from a single submission).

You start with a Word mail merge template like this:

When you run the Python mail merge script, you get customized Word documents like this with data from Central.

Thanks to pyODK, the official Python API client for ODK Central, the code is very straightforward!

In this snippet below, only data from approved submissions are included, but you can customize as you see fit (e.g., only submissions that have great_vibes=true).

with Client() as client:
    submissions = client.submissions.get_table(form_id="site_form")
    for submission in submissions["value"]:
        # only include approved submissions
        if submission["__system"]["reviewState"] == "approved":
            with MailMerge("template.docx") as document:
                document.merge(
                    site_name=submission["site_name"],
                    site_vibe=submission["site_details"]["vibe"],
                    instance_id=submission["meta"]["instanceID"],
                    submission_date=submission["__system"]["submissionDate"],
                    generation_date=datetime.now().strftime("%m-%d-%Y %H:%M:%S.%f"),
                )
                document.write(os.path.join("merged", f"{submission['site_name']}.docx"))

Want to try this yourself? You can find a complete example with sample template and sample output at https://github.com/getodk/pyodk/tree/master/docs/examples/mail_merge.

8 Likes