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)
workbook = xlsxwriter.Workbook('/home/Desktop/status.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()
return JsonResponse({'ok':'ok'})
如在我的views.py中的上述功能中所见,当在UI中单击按钮(Download Excel)时,请求被发送到此功能,并且我正在生成一个excel并保存暂时放在desktop folder中。
当单击“ 下载excel”按钮而不是将其保存在特定路径时,如何在用户界面的浏览器中为用户下载此excel。
Note:-我正在使用xlswriter模块生成Excel。
将工作簿写入BytesIO
,然后返回数据作为响应:
from io import BytesIO
# ...
output = BytesIO()
workbook = xlsxwriter.Workbook(output)
# ...
workbook.close()
return HttpResponse(
output.getvalue(),
content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
headers={'Content-disposition': 'attachment; filename=status.xlsx'},
)