开发者

How to: create .doc files using templates with django/python

I am writing a django application and there is something 开发者_JAVA百科I don't know how to do. Say you have a database with users and several .doc files you might want to send to those users (postal letters, not electronicaly). I am wondering if there is a way to automatically create those letters from templates using my user database to fill in some markers? (i.e. name, address, etc.)

I've heard of the "pod" python library but I've never used it. The documentation seems to say to use openoffice templates, but mine are in MS Word format. Since they are often updated by people who only use MS Office, I'm stuck.

Any help would be appreciated.

J.


There are many different ways to do this, depending on the context. Here are some ideas, ranked in decreasing order of difficulty.

  • Microsoft Word includes a facility for this, called Mail Merge. You can control Word from Python using COM hooks, by installing pywin32. This would do exactly the same as invoking Mail Merge by opening up Microsoft Word. This would have to be done on a Windows computer with Office installed, probably not your server. See http://bytes.com/topic/python/answers/165364-ms-word-mail-merge-automation, or Google "python mail merge".

  • OpenOffice uses Python as a macro language (I believe) and exposes an API using Python-UNO. You could make OpenOffice convert the files in to its format, and then use pod to perform the mail merge.

  • You could tell your users to give you data in a better format, such as OpenOffice templates.

  • You could export the users' data from Django, give it to the people writing the templates, and tell them to do their own mail merge.

Whatever you choose, this will not be easy.


Using mailmerge is easy and you can modify the template from a word doc.

http://pbpython.com/python-word-template.html

You can incorporate mail merge with a view as well. Here is an example where my_template1 is my word document template and there are fields called name and title in it.

def TestDocument2(request):
    template = os.path.join(os.path.dirname(__file__), 
    'templates/my_template1.docx')  

    document = MailMerge(template)
    document.merge(name='testcoy',
               title = 'My title',
               )
    f = io.BytesIO()
    document.write(f)
    length = f.tell()
    f.seek(0)
    response = HttpResponse(
        f.getvalue(),
        content_type='application/vnd.openxmlformats-
        officedocument.wordprocessingml.document'
         )
    response['Content-Disposition'] = 'attachment; filename=example.docx'
    response['Content-Length'] = length
    return response
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜