Django動態下載文件


前台提交查詢條件,下載符合條件的EXCEL數據文件,后端視圖中使用 xlwt 庫來返回,如:

objs = Units.objects.all()
# 創建 Workbook 時,如果需要寫入中文,請使用 utf-8 編碼,默認是 unicode 編碼。
wb = xlwt.Workbook(encoding='utf-8')
ws = wb.add_sheet('配件價格')
ws.write(0, 0, '配件編號')
ws.write(0, 1, '配件名稱')
ws.write(0, 2, '配件價格')
ws.write(0, 3, '商場')
excel_row = 1
for obj in objs:
    ws.write(excel_row, 0, obj.unitid)
    ws.write(excel_row, 1, obj.unitname)
    ws.write(excel_row, 2, obj.price)
    ws.write(excel_row, 3, obj.marketid)
    excel_row = excel_row + 1
# ------ 開始:這段代碼可以用下面注釋段替代,都是本應保存為文件格式的改成保存為數據流,以便返回前端下載
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=example.xls'
wb.save(response)
return response
# ------ 結束
"""
sio = StringIO.StringIO()
wb.save(sio)
response = HttpResponse(sio.getvalue(),content_type='application/vnd.ms-excel') 
response['Content-Disposition'] = 'attachment; filename=test.xls'          
return response
""" 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM