Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 652
INDER Avatar asked Oct 15 '25 16:10

INDER


2 Answers

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.

like image 107
Kostas Livieratos Avatar answered Oct 17 '25 10:10

Kostas Livieratos


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.

like image 35
LNI Avatar answered Oct 17 '25 09:10

LNI



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!