视图函数export_persons
引入导出excle相关库
import xlwt
def export_persons(request):
# 获取数据库中的所有Project对象
persons = m1.Project.objects.all()
# 创建Excel文件
book = xlwt.Workbook(encoding='utf-8', style_compression=0)
sheet = book.add_sheet('Sheet', cell_overwrite_ok=True)
# 写入表头
sheet.write(0, 0, '项目ID')
sheet.write(0, 1, '题目')
sheet.write(0, 2, '开始时间')
sheet.write(0, 3, '结束时间')
sheet.write(0, 4, '创建人')
# 写入数据
row_num = 1
for person in persons:
sheet.write(row_num, 0, person.id)
sheet.write(row_num, 1, person.title)
sheet.write(row_num, 2, person.start_time)
sheet.write(row_num, 3, person.end_time)
sheet.write(row_num, 4, person.create_person_id)
row_num += 1
# 保存文件并返回HttpResponse对象
response = HttpResponse(content_type='application/ms-excel')
response['Content-Disposition'] = 'attachment; filename="persons.xls"'
book.save(response)
return response
标签:sheet,persons,excel,导出,django,write,person,num,row
From: https://www.cnblogs.com/yuanyongsheng/p/18075815