How can I generate and excel output from django python

Viewed 48

Given a query set from my database, I am trying to output the results into an excel file. I have tried two versions of code... the code executes properly without outputting any error messages, but the excel file is not outputted, any suggestions on where I went wrong.

import pandas as pd
import csv, io, xlsxwriter
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse, FileResponse

def print_excel(request)
    products = Product.objects.all()
    df = pd.DataFrame(list(products.values()))
    excel_file = io.BytesIO()
    xlwriter = pd.ExcelWriter(excel_file, engine='xlsxwriter')
    df.to_excel(xlwriter, 'sheetname')
    xlwriter.save()
    #xlwriter.close()
    excel_file.seek(0)

    response = HttpResponse(excel_file.read(), content_type='application/ms-excel vnd.openxmlformats-officedocument.spreadsheetml.sheet')
    # set the file name in the Content-Disposition header
    response['Content-Disposition'] = 'attachment; filename=myfile.xls'
    return response  

I also tried the below approached where I tried to output an excel with the string rows

import pandas as pd
import csv, io, xlsxwriter
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse, FileResponse

def print_excel(request)
    buffer = io.BytesIO()
    workbook = xlsxwriter.Workbook(buffer)
    worksheet = workbook.add_worksheet()
    worksheet.write('A1', "rows")
    workbook.close()
    buffer.seek(0)

    return FileResponse(buffer, as_attachment=True, filename='myfile.xlsx')

The two codes executes properly but I cant locate the excel file created.

1 Answers

The code is fine, the problem might be with the get request... If you are using a fetch request via JavaScript, you will the error. For the Fileresponse and HttpResponse to work properly and generate the required files ensure the get request is generate directly from the html template i,e use <a href="">Generate Excel</a>

Related