3

我需要根据数据库中的信息生成 .odt 或 .docx 文件。假设我有一个模型:

class Contact(models.Model):
    first_name = models.CharField()
    last_name = models.CharField()
    email = models.EmailField()

我希望用户能够生成包含该信息以及其他一些文本的办公文档。我查看了这个使用 python-docx 的示例,它让我了解了如何生成该文档。但我不知道这个文件保存在哪里,甚至是创建的。在我的模板中,我有一个链接:

<a href="{{ contact.generate_docx }}">generate .docx document</a>

wheregenerate_docx()运行的代码可以从我上面提供的链接中找到。

如何实现我的系统,以便在单击链接时,应根据数据库中的数据创建或更新文档,然后将其下载到用户计算机?将该文档保存到数据库不是强制性的,但我也有兴趣了解如何执行此操作。

4

3 回答 3

3

你可以在一个 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
于 2015-01-11T18:23:35.970 回答
2

您可以使用 Py2docx ( https://github.com/rafaels88/py2docx ) 构建您的 .docx 文件。将您的代码放在视图上,然后您可以执行以下操作:

# Here goes the Py2docx code
# After save the .docx file, do this:

file_docx = open("path/file.docx", 'r')
response = HttpResponse(mimetype='text/html')
response['Content-Disposition'] = 'attachment; filename=file_name.docx'
response['Content-Encoding'] = 'UTF-8'
response['Content-type'] = 'text/html; charset=UTF-8'
response.write(file_docx.read())
file_docx.close()
return response

然后,在 HTML 上创建指向您的视图 url 的链接。

于 2014-04-04T15:14:40.127 回答
0

如果pdf也是可接受的格式,您可以考虑使用django-wkhtmltopdf. 它将允许您创建一个普通页面,并将其转换为pdf使用 webkit 的二进制形式。

于 2014-03-12T23:37:32.633 回答