microsoft word editing in python

Python docx-mailmerge and mailmerger is one of the best library in the python world. To Edit or make a new document in ms-word and need to render the ms-word file, so docx mail-merger is the best option. So in this article we show how to render the microsoft word file in django.

How to render the microsoft word file in django

>>simple syntax

$ pip install docx-mailmerge

pip install docx-mailmerge command install all the necessary files python library.

from mailmerge import MailMerge
with MailMerge('input.docx') as document:

This is how to use mailmerge.

Now lets us take an example for better understanding

Word Merge Fields

In order for docx-mailmerge to work correctly, you need to create a standard Word document and define the appropriate merge fields. The examples below are for Word 2010. Other versions of Word should be similar or may be different in future. It actually took me a while to figure out this process but once you do it a couple of times, it is pretty simple.

Start Word and create the basic document structure. Then place the cursor in the location where the merged data should be inserted and choose Insert -> Quick Parts -> Field..:


From the Field dialog box, select the “MergeField” option from the Field Names list. In the Field Name, enter the name you want for the field. In this case, we are using Business Name.

render the microsoft word file in django

Simple Merge

Once you have the Word document created, merging the values is a simple operation. The code below contains the standard imports and defines the name of the Word file. In most cases, you will need to include the full path to the template but for simplicity, I am assuming it is in the same directory as your python scripts:

from __future__ import print_function
from mailmerge import MailMerge
from datetime import date

template = "Practical-Business-Python.docx"

To create a mailmerge document and look at all of the fields:

document = MailMerge(template)
{'purchases', 'Business', 'address', 'discount',
 'recipient', 'date', 'zip', 'status', 'phone_number',
 'city', 'shipping_limit', 'state'}

To merge in the values and save the results, use document.merge with all of the variables assigned a value and document.write to save the output:

    Business='Cool Shoes',
    address='1234 Main Street',
    recipient='Mr. Jones')


Here is a sample of what the final document will look like:

Final Document

This is a simple document but pretty much anything you can do in Word can be turned into a template and populated in this manner.

This is how render the microsoft word file in django. For more information about this library please read documentation.

post credit-


Read also->How to surf deep web on your computer safely


Please enter your comment!
Please enter your name here