Downloadable docx file in Django

前端 未结 4 743
慢半拍i
慢半拍i 2020-12-18 16:18

My django web app makes and save docx and I need to make it downloadable. I use simple render_to_response as below.

return render_to_response(\"         


        
相关标签:
4条回答
  • 2020-12-18 16:23

    Yep, a cleaner options, as stated by wardk would be, using 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
    
    0 讨论(0)
  • 2020-12-18 16:26

    Is it possible, that your path to 'test.docx' contains non-ascii-characters? Did you check all local variables on the django debug page?

    What I did to download an xml file was not to create the file on disc but to use a memory file (saves me from dealing with file systems, path, ...):

        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
    

    Maybe you can adapt this to your docx-situation.

    0 讨论(0)
  • 2020-12-18 16:37

    Try with this response:

    response = HttpResponse(mydata, mimetype='application/vnd.ms-word')
    response['Content-Disposition'] = 'attachment; filename=example.doc'
    return response 
    
    0 讨论(0)
  • 2020-12-18 16:43

    I managed to generate a docx document from a django view thanks to python-docx.

    Here is an example. I hope it helps

    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
    
    0 讨论(0)
提交回复
热议问题