Django中可下载的docx文件

brs*_*gic 1 python django python-docx

我的django网络应用程序制作并保存docx,我需要让它可下载.我用简单render_to_response如下.

return render_to_response("test.docx", mimetype='application/vnd.ms-word')
Run Code Online (Sandbox Code Playgroud)

但是,它会引发错误 'utf8' codec can't decode byte 0xeb in position 15: invalid continuation byte

我无法将此文件作为静态服务,所以我需要找到一种方法来为它提供服务.真的很感激任何帮助.

Vit*_*tas 7

是的,使用https://python-docx.readthedocs.org/,如wardk所述,更清洁的选择:

from docx import Document
from django.http import HttpResponse

def download_docx(request):
    document = Document()
    document.add_heading('Document Title', 0)

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document')
    response['Content-Disposition'] = 'attachment; filename=download.docx'
    document.save(response)

    return response
Run Code Online (Sandbox Code Playgroud)


luc*_*luc 6

由于python-docx,我设法从django视图生成docx文档.

这是一个例子.我希望它有所帮助

from django.http import HttpResponse
from docx import Document
from cStringIO import StringIO

def your_view(request):
    document = Document()
    document.add_heading(u"My title", 0)
    # add more things to your document with python-docx

    f = StringIO()
    document.save(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
Run Code Online (Sandbox Code Playgroud)