Generate Excel File in Django and Write it on Memory

I’m creating report to excel format using XlsxWriter, and here is some trick to generate excel file on memory instead of write the file to disk before we throw it to http response attachment.

import xlsxwriter

    import cStringIO as StringIO
except ImportError:
    import StringIO

from django.http import HttpResponse

def download_view(request):
    # Create file on memory
    output = StringIO.StringIO()

    # Generate excel.
    workbook = xlsxwriter.Workbook(output, {'in_memory': True})
    worksheet = workbook.add_worksheet()
    worksheet.write('A1', 'Hello export.')

    # Construct response.
    response = HttpResponse(, content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=your_file_name.xlsx'
    return response


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.