Djang中可下载的docx文件

2024-05-23 14:25:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我的django web应用程序生成并保存docx,我需要使其可下载。 我使用简单的render_to_response如下。

return render_to_response("test.docx", mimetype='application/vnd.ms-word')

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

我不能把这个文件当作静态文件,所以我需要找到一种方法把它当作静态文件。 非常感谢你的帮助。


Tags: 文件todjangotestweb应用程序returnapplication
3条回答

尝试此响应:

response = HttpResponse(mydata, mimetype='application/vnd.ms-word')
response['Content-Disposition'] = 'attachment; filename=example.doc'
return response 

由于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

是的,一个更干净的选项,正如wardk所说,使用https://python-docx.readthedocs.org/

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

相关问题 更多 >