4

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 2

3

It's not as complicated as you may think. In fact, as I understand, you have a Django model and you need to export some instances' data in an .xlsx file for example.

I'd suggest the following simple solution:

import openpyxl
from openpyxl.utils import get_column_letter
from django.http.response import HttpResponse

def method(request, **kwargs):
    queryset = ModelName.objects.filter()   # adjust accordingly

    response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    response['Content-Disposition'] = 'attachment; filename=this-is-your-filename.xlsx'
    wb = openpyxl.Workbook()
    ws = wb.get_active_sheet()
    ws.title = "Your Title"

    row_num = 0

    columns = [
        ("ID", 5),
        (u'Name', 20),
    ]

    for col_num in range(len(columns)):
        c = ws.cell(row=row_num + 1, column=col_num + 1)
        c.value = columns[col_num][0]
        ws.column_dimensions[get_column_letter(col_num + 1)].width = columns[col_num][1]

    for obj in queryset:
        row_num += 1
        row = [
            obj.pk,
            obj.name,
        ]
        for col_num in range(len(row)):
            c = ws.cell(row=row_num + 1, column=col_num + 1)
            c.value = row[col_num]

    wb.save(response)
    return response

Please keep in mind that you need to install with pip install openpyxl the openpyxl lib first.

Sign up to request clarification or add additional context in comments.

6 Comments

Actually I am using xlsxwriter to generate excel file and save it on the server. Can I send this saved .xlsx file as a http response ?
I cannot think of a reason you cannot do it. You have to set the Content-Disposition HTTP header in your response, as well as the correct content_type.
Ok thanks ....I'll try this once ..and do I need to add anything in html too or the return response would automatically Download the file
It should automatically prompt the user to download the file
I am getting the response at the website but download prompt is'nt appearing
|
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.