XlsxWriter object save as http response to create download in Django

前端 未结 3 1899
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-30 19:42

XlsxWriter object save as http response to create download in Django?

3条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 20:05

    A little update on @alecxe response for Python 3 (io.BytesIO instead of StringIO.StringIO) and Django >= 1.5 (content_type instead of mimetype), with the fully in-memory file assembly that has since been implemented by @jmcnamara ({'in_memory': True}) !
    Here is the full example :

    import io
    
    from django.http.response import HttpResponse
    
    from xlsxwriter.workbook import Workbook
    
    
    def your_view(request):
    
        output = io.BytesIO()
    
        workbook = Workbook(output, {'in_memory': True})
        worksheet = workbook.add_worksheet()
        worksheet.write(0, 0, 'Hello, world!')
        workbook.close()
    
        output.seek(0)
    
        response = HttpResponse(output.read(), content_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        response['Content-Disposition'] = "attachment; filename=test.xlsx"
    
        output.close()
    
        return response
    

提交回复
热议问题