Return Excel file from django view to html for downloading at client

Viewed 4688

I have a django app in which excel file is generated at server side and I want that to be downloaded at client. I am sending​ request through Ajax call in JavaScript that goes to server generates excel which needs to be downloaded. The view should generate http response that sends excel file to html that could be downloaded to a file at client

2 Answers

I had to complete this exact task and ended up using the following method. Instead of using an AJAX call, I just do

window.location.pathname = "/relative/path/to/url/"

within Javascript click handler for the button.

Within Django, I am using the following code (I am using XlsxWriter but you could use whatever you wish for creating XLSX file):

    excel_file = BytesIO()
    workbook = xlsxwriter.Workbook(excel_file)

    # Code to populate the workbook

    # Here comes the magic
    workbook.close()
    excel_file.seek(0)
    response = HttpResponse(excel_file.read(),
                            content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=somename.xlsx'
    return response

When called this way, the created Excel file is downloaded and the user remains on the calling page, which is the exact behavior I wanted.

Related