I have a Download excel button in the UI, when clicked excel should get downloaded. Following are the code snippets for the same.
To my surprise, Ajax request returns 200 OK, but an error event is fired instead of success. Not able to trace back the root cause.
views.py
def excel(request):
ans = request.POST.getlist('ans[]')
ans_final=[]
rows = request.POST.get('rows')
for each_ele in ans:
each_ele = each_ele.split('.')
each_ele[0] = each_ele[0][:-2]
each_ele[1] = each_ele[1][:-2]
fin = each_ele[0]+' - '+each_ele[1]
ans_final.append(fin)
output = BytesIO()
workbook = xlsxwriter.Workbook(output)
# workbook = xlsxwriter.Workbook('/home/sai_avinash/Desktop/hello.xlsx')
worksheet = workbook.add_worksheet('Test_Data')
bold = workbook.add_format({'bold': True})
for i in range(len(ans_final)):
worksheet.write(0, i,ans_final[i],bold)
row_index=1
row_count = int(rows)
while(row_count):
col_index=0
for each_ele in ans:
worksheet.write(row_index, col_index, eval(each_ele))
col_index += 1
row_index += 1
row_count -= 1
workbook.close()
output.seek(0)
# return JsonResponse({'ok':'ok'})
response = HttpResponse(
output,
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
)
response['Content-Disposition'] = 'attachment; filename=django_simple.xlsx'
return response
js file
$('body').on('click', '.excel', function () {
var ok = ans
rows = $('#hmm').val()
$.ajax({
type: "POST",
url: "/excel",
data: {'ans':ok, 'rows':rows},
dataType: "json",
success: function (data) {
// alert("Success")
},
error: function (e) {
debugger
// console.log(e)
alert("Error")
}
});
});