django 记一次数据库文件下载excel

from xlwt import Workbook
from django.http import FileResponse

class FormToExcel(APIView):
def get(self,request):
data_list = ProductionHour.objects.all()
production = ProductionListSerializers(data_list, many=True)
ws = Workbook() # 创建工作薄
w = ws.add_sheet(u"生产二部报工模板") # 设置sheet名称
title = ["生产日期", "厂区", "客户名称", "班别", "班次", "生产订单号", "行号", "产品编码", "产品名称", "总人数",
"劳务工人数", "正式工人数", "作业工时(分钟/人)", "机器调试", "等外部料", "等内部料", "设备维修", "其他",
"作业RT", "劳务工时", "正式工时", "作业工时", "生产损时", "总工时", "生产数量", "入库数量", "未入库数量",
"入库编码", "未入库原因", "入库类型", "返工/报废原因", "备注"]
for i in range(len(title)):
w.write(0,i,title[i])
# 把需要导出的数据写到文件中
excel_row = 1
for obj in production.data:
w.write(excel_row, 0, obj["production_date"])
w.write(excel_row, 1, obj["place_name"])
w.write(excel_row, 2, obj["customer_name"])
w.write(excel_row, 3, obj["class_ban"])
w.write(excel_row, 4, obj["shifts_dis"])
w.write(excel_row, 5, obj["prodiction_order"])
w.write(excel_row, 6, obj["line_number"])
w.write(excel_row, 7, obj["product_encoding"])
w.write(excel_row, 8, obj["product_name"])
w.write(excel_row, 9, obj["people_number"])
w.write(excel_row, 10, obj["people_labors"])
w.write(excel_row, 11, obj["people_workers"])
w.write(excel_row, 12, obj["work_hours"])
w.write(excel_row, 13, obj["machine_debug"])
w.write(excel_row, 14, obj["wait_outside_material"])
w.write(excel_row, 15, obj["wait_inside_material"])
w.write(excel_row, 16, obj["equipment_maintenance"])
w.write(excel_row, 17, obj["other_problem"])
w.write(excel_row, 18, obj["job_hours"])
w.write(excel_row, 19, obj["labors_hours"])
w.write(excel_row, 20, obj["workers_hours"])
w.write(excel_row, 21, obj["working_hours"])
w.write(excel_row, 22, obj["product_loss_time"])
w.write(excel_row, 23, obj["sum_working_hours"])
w.write(excel_row, 24, obj["production_number"])
w.write(excel_row, 25, obj["warehousing_number"])
w.write(excel_row, 26, obj["no_warehousing_number"])
w.write(excel_row, 27, obj["warehousing_encoding"])
w.write(excel_row, 28, obj["no_warehousing_reason_dis"])
w.write(excel_row, 29, obj["warehousing_type_dis"])
w.write(excel_row, 30, obj["rework_reason"])
w.write(excel_row, 31, obj["remarks"])
excel_row += 1
ws.save('apps/OperateList/v1/file/prodiction_list.xls')
file_path = 'apps/OperateList/v1/file/prodiction_list.xls'
data = open(file_path, 'rb')
return FileResponse(data, content_type="application/vnd.ms-excel")
原文地址:https://www.cnblogs.com/zxs117/p/12604769.html