Search code examples
pythonpandasms-wordmailmergepython-docx

Write Word mail merge fields to MS Word with Python


I've cranked a bunch of code with Python and Pandas, which is all groovy and gravy. But now I have to populate a bunch of tables in a word document. Ideally I'd like to write a bunch of Mergefields to a table and then merge it through word with the csv kicked out by Pandas.

I've started with python-docx, but there is nothing in the documentation about writing mergefields, unless I'm mistaken. Something like this would be the bees Knees:

 document = Document()

 document.add_heading('Does this merge thing work', 0)

 table = document.add_table(rows=1, cols=3)
 hdr_cells = table.rows[0].cells
 hdr_cells[0].text = 'Qty'
 hdr_cells[1].text = 'Id'
 hdr_cells[2].text = 'Desc'
 row_cells = table.add_row().cells
 row_cells[0].text = "MERGEFIELD yo " #doesn't work, just string. 
 row_cells[1].MERGEFIELD = "Funky"    #MERGEFIELD not a table object
 row_cells[2].mailMerge = "Nice"      #This type of thing would be dreamy

I'm also familiar with win32com, but I can't find documentation of writing a merge field anywhere. I've recorded a macro in word when inserting a mergefield and the VBA looks like:

  Selection.Fields.Add Range:=Selection.Range, Type:=wdFieldEmpty, Text:= _
    "MERGEFIELD  obviosulyyournotagolfer", PreserveFormatting:=True

even just writing a big list of mergefields to a document would be a big help. Any input would be much appreciated.

I've also been playing with docx-mailmerge, but from what I can tell it only allows you to merge data to already existing merge fields. Thanks for your help!


Solution

  • Are you looking for something like python-docx-template? It allows you to create jinja2-like templates for Microsoft Word Documents. That could involve creating tables or other auto-populated fields. It also allows you to format and style your document the way you want and ha

    Here's an example:

    {%tr for a in alerts %}
    {{ a.date }}    {% cellbg a.bg %}{{ a.type }}   {{r a.desc }}
    {%tr endfor %}
    

    That's something that might show up in the word doc. There are other table examples like that on github.