Using a Template
You could hand-build a document and automate all the formatting, but that would be tedious. Far better to use a Word template and just put in what you need from your Python code. For the next example, we’ve created a template called Pythonics.dot. This has a fancy header, page numbers, and borders. It could also contain section headings, a table of contents, standard text, or whatever you want. Using a template is a huge leap forward in productivity. Figure 10.1 shows ours.
![]() |
More important, a template allows you to separate the software development from the page layout. An artistically challenged developer could provide a basic template with the required elements, and turn it over to the marketing department to define the styles and boilerplate text. If she also delivers a Python test script containing example data, the marketing person can regularly test whether the program still runs while he is modifying the template.
To create a document based on a template, you need to modify only one line:
>>> myDoc = myWord.Documents.Add(template=MYDIR + '\\pythonics.dot')
Note the use of keyword arguments. Many of the Office functions (like
Documents.Add) take literally dozens of arguments,
and entering them every time would be tedious. Fortunately, Python
also supports named arguments. However, you need to watch the
case: most Word arguments have ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access
