Home python Python: Creating Word Documents by Template

Python: Creating Word Documents by Template




Script task Open Word document template (DOT, DOC, DOCX). Finding specially marked species {change-this1}, replace them (in the same styles that there was a replaceable text). Save the document in the format suitable for printing and editing preferably doc \ docx.

Question: What libraries / built-in Python capabilities are best suited for this task. As I understand the format closed and simply “opening” a file as “text” does not cost.

UPD: Found a library that seems to be able to open Word documents http://python-docx.readthedocs.org/ So far I study its capabilities.

Answer 1, Authority 100%

There is a library – Python-DocX-Template whose purpose is to create .docx Documents using Jinja2 templates.

Installs the PIP Install DocXtpl command.

Used – Create a document (not HTML template, and DOCX document) As usual, but insert {{& lt; var_name & gt to the place of variables. }} jinja2 tags. Then:

from docxtpl import docxtemplate
doc = docxtemplate ("My_Template.docx")
CONTEXT = {'VAR_NAME': "Hello World!" }
Doc.Render (Context)
doc.save ("generated.docx")

Result – In the generated document, tags will be replaced with the desired values.

Application area is quite limited, but nevertheless in some cases it may be convenient.

Answer 2, Authority 50%

Old binary .doc Formats Even different versions of MS Word can understand differently (it looks good in one place, breaks in the other). Easy way to automate work with Word documents if MS Word is available is to execute examples in Word and write it as a VBA macro that can be transmitted easily into Python if necessary, for example: Using Win32Com.client in Python How to Find and Replace Multiple Text .

In order not to depend on the Word, if there is a possibility, then it is better as part of the .docx format to stay and try the package python-docx .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions