Django导出excel
import xlwt
workbook = xlwt.Workbook(encoding='utf8')
ws = workbook.add_sheet('monitor_sheet')
data = models.PcMonitor_Line.objects.all()
ser = TableSerialize(instance=data, many=True)
site_names = []
site_fields = models.SitTable._meta.fields
for item in site_fields:
site_names.append(item.name)
# 给id给去掉
site_names.pop(0)
# 封装临时的对象
tem_site_obj = {}
for item in site_names:
tem_site_obj[item] = ""
global_list = []
for item in ser.data:
tem_data = dict(item)
tem_dict = tem_data.get('children') if bool(tem_data.get("children")) else tem_site_obj
tem_data.update(tem_dict)
del tem_data['children']
all_values = tem_data.values()
titles = tem_data.keys()
global_list.append(all_values)
# 封装表格标题
for key,value in enumerate(tuple(titles)):
ws.write(0,key,value)
#封装具体的内容
for key,value in enumerate(tuple(global_list)):
for k, v in enumerate(value):
ws.write(key+1,k,v) #第一个是第几行,第二个是第几行的第几列,最后一个参数是值
# 设置响应的头
response = HttpResponse(content_type='application/msexcel')
# 设置Disposition 表示是一个附件,是可以下载的
response['Content-Disposition'] = 'attachment; filename=monitor_data.xls'
# 保存数据,供前端来导出
workbook.save(response)
# 返回数据
return response
技术改变一切