0

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")
    }
});

});

Mahesh
  • 1,117
  • 2
  • 23
  • 42
  • what would help is to know what the error is (hint: `e` holds the error) – Jaromanda X Feb 21 '20 at 11:24
  • your code expects JSON response (`dataType: "json",`) ... you're returning `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` from the server - I think the problem is clear now – Jaromanda X Feb 21 '20 at 11:25
  • @JaromandaX, the response text in e is a long string with special characters..... and btw, i tried changing datatype from 'json' to 'string' but still i am facing the same issue – Mahesh Feb 21 '20 at 11:38
  • the jquery ajax error callback function "signature" is `Function( jqXHR jqXHR, String textStatus, String errorThrown )` ... so in your case, `e` will NOT be the error, try `error: function(jq, status, e)` ... now `e` will show you the error thrown – Jaromanda X Feb 21 '20 at 11:42
  • @JaromandaX, wow... Got to know the error and i changed datatype from string to text, and now data is returned in success, my doubt now is how do i convert this data string into excel... Pls suggest – Mahesh Feb 21 '20 at 12:10
  • Javascript cannot directly download a file to your computer's disk. See [this](https://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax) for a complete answer on how to circumvent this. [This blog post](http://johnculviner.com/jquery-file-download-plugin-for-ajax-like-feature-rich-file-downloads/), linked in the same answer, explains how this works. – dirkgroten Feb 21 '20 at 12:18
  • `how do i convert this data string into excel` that's a completely different question – Jaromanda X Feb 21 '20 at 22:33
  • @JaromandaX, I know its a different question, but can you please help how to generate excel fro this data string? – Mahesh Feb 22 '20 at 09:40
  • this "sring" IS the (presumably excel) worksheet the python created and sent. I would try sending it and receiving it as a arraybuffer using native xmlhttprequest or fetch, since they support arraybuffer – Jaromanda X Feb 22 '20 at 21:19

0 Answers0