我的 django 网络应用程序制作并保存了 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
我无法将此文件作为静态文件提供,因此我需要找到一种方法将其作为静态文件提供。 非常感谢您的帮助。
请您参考如下方法:
是的,正如 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
