Search code examples
pythondjangoexcelhttpresponsexlsxwriter

XlsxWriter object save as http response to create download in Django


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


Solution

  • I think you're asking about how to create an excel file in memory using xlsxwriter and return it via HttpResponse. Here's an example:

    try:
        import cStringIO as StringIO
    except ImportError:
        import StringIO
    
    from django.http import HttpResponse
    
    from xlsxwriter.workbook import Workbook
    
    
    def your_view(request):
        # your view logic here
    
        # create a workbook in memory
        output = StringIO.StringIO()
    
        book = Workbook(output)
        sheet = book.add_worksheet('test')       
        sheet.write(0, 0, 'Hello, world!')
        book.close()
    
        # construct response
        output.seek(0)
        response = HttpResponse(output.read(), mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
        response['Content-Disposition'] = "attachment; filename=test.xlsx"
        
        return response