import io
from django.http import HttpResponse
import xlwt
import os
from django.views import View

class DownExcelView(View):
def get(self, request):
list_obj = User.objects.all()
# 设置HTTPResponse的类型
response = HttpResponse(content_type='application/vnd.ms-excel')
response['Content-Disposition'] = 'attachment;filename=' + 'userinfo' + '.xls'
"""导出excel表"""
if list_obj:
# 创建工作簿
ws = xlwt.Workbook(encoding='utf-8')
# 添加第一页数据表
w = ws.add_sheet('sheet1') # 新建sheet(sheet的名称为"sheet1")
# 写入表头
w.write(0, 0, u'用户编号')
w.write(0, 1, u'用户名')
# 写入数据
excel_row = 1
for obj in list_obj:
user_id = obj.id
username = obj.username
# 写入每一行对应的数据
w.write(excel_row, 0, user_id)
w.write(excel_row, 1, username)

#w.write(excel_row, 1, 导出的字段名)
excel_row += 1
# 写出到IO
output = io.BytesIO()
ws.save(output)
# 重新定位到开始
output.seek(0)
response.write(output.getvalue())
return response

posted on 2021-04-16 20:15  v3174  阅读(127)  评论(0)    收藏  举报