Django中可下载的docx文件

时间:2013-10-16 09:45:20

标签: python django python-docx

我的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

之类的错误

我无法将此文件作为静态服务,因此我需要找到一种方法来为此服务。 真的很感激任何帮助。

5 个答案:

答案 0 :(得分:7)

是的,如使用https://python-docx.readthedocs.org/所述,使用documentation

更清洁的选项
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

答案 1 :(得分: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

答案 2 :(得分:1)

尝试此回复:

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

答案 3 :(得分:1)

你的'test.docx'路径是否可能包含非ascii字符?您是否在django调试页面上检查了所有局部变量?

我下载xml文件所做的不是在光盘上创建文件,而是使用内存文件(使我免于处理文件系统,路径......):

    memory_file = StringIO.StringIO()
    memory_file.writelines(out) #out is an XMLSerializer object in m case

    response = HttpResponse(memory_file.getvalue(), content_type='application/xml')
    response['Content-Disposition'] = 'attachment; filename="my_file.xml"'
    response['Content-Length'] = memory_file.tell()
    return response

也许你可以根据你的docx情况进行调整。

答案 4 :(得分:1)

用于下载已存在的 DOCX 文件

我稍微修改了@luc 的回答。他的帖子让我成功了 98%。我进行了更改,因为我不需要创建 Word 文件。我的用法只是传递文件服务器上存在的一个,然后准备下载。

因为下载的文档已经存在。

def download(request):
filepath = os.path.abspath(r"path\to\file.docx")
print('SLA FILE: ', filepath)
if os.path.exists(filepath):
    with open(filepath, 'rb') as worddoc: # read as binary
        content = worddoc.read() # Read the file
        response = HttpResponse(
            content,
            content_type='application/vnd.openxmlformats-officedocument.wordprocessingml.document'
        )
        response['Content-Disposition'] = 'attachment; filename=download_filename.docx'
        response['Content-Length'] = len(content) #calculate length of content
        return response
else:
    return HttpResponse("Failed to Download SLA")