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

try:
    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.')
    workbook.close()

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

Reference: http://stackoverflow.com/questions/16393242/xlsxwriter-object-save-as-http-response-to-create-download-in-django

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s