导出数据至excel
使用xlwt包,可以非常方便的将数据库中的数据导出到excel中去
import xlwt
# 导出到excel
def export_to_xls(request):
# 从数据库查询数据
contact_list = models.test.objects()
# 创建工作簿
f = xlwt.Workbook(encoding='utf-8')
# 创建一个sheet
sheet1 = f.add_sheet(u'任务单', cell_overwrite_ok=True)
# 初始化第一行
sheet1.write(0, 0, "任务单号")
sheet1.write(0, 1, "任务标题")
sheet1.write(0, 2, "任务创建人")
sheet1.write(0, 3, "任务执行人")
sheet1.write(0, 4, "任务验收人")
sheet1.write(0, 5, "任务优先级")
sheet1.write(0, 6, "创建日期")
sheet1.write(0, 7, "截止日期")
sheet1.write(0, 8, "任务单状态")
# 将数据插入到表格中
row = 1
for contact in contact_list:
sheet1.write(row, 0, contact.task_code)
sheet1.write(row, 1, contact.task_title)
sheet1.write(row, 2, contact.task_creator)
sheet1.write(row, 3, contact.task_executor)
sheet1.write(row, 4, contact.task_tester)
sheet1.write(row, 5, contact.task_level)
sheet1.write(row, 6, contact.task_date)
sheet1.write(row, 7, contact.task_deadline)
sheet1.write(row, 8, contact.task_status)
row += 1
sio = BytesIO()
f.save(sio)
sio.seek(0)
response = HttpResponse(sio.getvalue(), content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment; filename=test_task.xls'
response.write(sio.getvalue())
return response
该文章对你有帮助吗,求分享转发: 分享到QQ空间 分享给QQ好友