XlsxWriter object save as http response to create download in Django

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

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

3条回答
  •  无人及你
    2020-11-30 20:08

    When it comes to Django, you can even do without the whole StringIO shenanigans. HttpResponse behaves just like a StringIO in that respect:

    from django.http import HttpResponse
    from xlsxwriter.workbook import Workbook
    
    def your_view(request):
        # your view logic here
    
        # create the HttpResponse object ...
        response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
        response['Content-Disposition'] = "attachment; filename=test.xlsx"
    
        # .. and pass it into the XLSXWriter
        book = Workbook(response, {'in_memory': True})
        sheet = book.add_worksheet('test')       
        sheet.write(0, 0, 'Hello, world!')
        book.close()
    
        return response
    

    Addendum: You need to specify {'in_memory': True} or you might get HttpResponse has no attribute seek(). Thanks @Jeb

提交回复
热议问题