你可以在一个 docx 文件中使用 django 模板语言,这实际上是一个 xml 文件的 zip 存档,然后通过模板引擎运行相应的 xml 文件。我在这里得到了这个想法:http ://reinout.vanrees.org/weblog/2012/07/04/document-automation.html
不过说起来容易做起来难。最终,我让它在 python3 中运行,如下所示:
from zipfile import ZipFile
from io import BytesIO
from django.template import Context, Template
def render_to_docx(docx, context):
tmp = BytesIO()
with ZipFile(tmp, 'w') as document_zip, ZipFile(docx) as template_zip:
template_archive = {name: template_zip.read(name) for name in template_zip.namelist()}
template_xml = template_archive.pop('word/document.xml')
for n, f in template_archive.items():
document_zip.writestr(n, f)
t = Template(template_xml)
document_zip.writestr('word/document.xml', t.render(Context(context)))
return tmp
在视图中:
response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
response['Content-Disposition'] = 'attachment; filename=document.docx'
zipfile = render_to_docx('template.docx'), context_dictionary)
response.write(zipfile.getvalue())
return response