safesite/safesite/export.py

768 lines
33 KiB
Python

from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm, Inches, Pt
from openpyxl import Workbook, load_workbook
from openpyxl.drawing.image import Image
from .models import User,Trouble,Dickey,Partment,Dicclass,Train,Drill,TroubleAccess,Group,Yjyc,ExamPaper,ExamPaperDetail,Question,Operation,Operzyry,Operspxq,Fxcs,Suggest,Suggestflow,Trainuser,Miss
from datetime import datetime,date
import base64
import os
from django.conf import settings
from django.utils.six import BytesIO
from django.http import HttpResponse
import xlsxwriter
import PIL
dirname = settings.BASE_DIR +'/'
def exportdoc2(a,data):
if a == 'ks':
data['dcsj'] = datetime.now()
#开始生成word
doc = DocxTemplate(dirname + "safesite/exportemp/ks.docx")
doc.render(data)
filename = data['num']
url = 'media/export/' + filename +'.docx'
filepath = dirname + url
doc.save(filepath)
return url
elif a == 'gc':
data['dcsj'] = datetime.now()
data['looktime'].replace("T"," ")
data['looktime2'].replace("T"," ")
#开始生成word
doc = DocxTemplate(dirname + "safesite/exportemp/gc.docx")
data['lookimgx']=[]
if data['lookimg']:
for i in data['lookimg']:
data['lookimgx'].append(InlineImage(doc,dirname + i,width=Mm(40)))
doc.render(data)
filename = data['looknum']
url = 'media/export/' + filename +'.docx'
filepath = dirname + url
doc.save(filepath)
return url
def exportdoc(a,id):
if a == 'yh':
troubleid = id
a = Trouble.objects.filter(troubleid=troubleid)
x = a.values('yhnum','fxr__name','yhms','yhzt','fxsj','tbsj','yhlb__dickeyname','yhpg__dickeyname','yhdd','fxbm__partname','yhdj__dickeyname','yhpg__dickeyname',
'jclx__dickeyname','yhlx__dicname','yyfx','zgcs','yhtp','zghtp','zgms','zgbm__partname','zgr__name','zgqx')[0]
yhzt__display = a[0].get_yhzt_display()
x['yhzt__display'] = yhzt__display
b = TroubleAccess.objects.filter(troubleid=a[0]).order_by('accesssj').values('clr__name','opinion','action','accesssj')
x['lcxq'] = list(b)
x['yhtp'] = x['yhtp'].split('?')
x['zghtp']= x['zghtp'].split('?')
x['dcsj'] = datetime.now()
for key in x:
if x[key] == None:
x[key] = ''
#开始生成word
doc = DocxTemplate(dirname + "safesite/exportemp/yhdc.docx")
x['yhtps']= []
if x['yhtp']==['']:
x['yhtps']= [{'yhtp':''}]
else:
for i in x['yhtp']:
x['yhtps'].append({'yhtp':InlineImage(doc,dirname + i,width=Mm(40))})
x['zghtps']=[]
if x['zghtp']==['']:
x['zghtps']= [{'zghtp':''}]
else:
for i in x['zghtp']:
x['zghtps'].append({'zghtp':InlineImage(doc,dirname + i,width=Mm(40))})
doc.render(x)
filename = x['yhnum']
url = 'media/export/' + filename +'.docx'
filepath = dirname + url
doc.save(filepath)
return url
elif a=='px':
trainid = id
a = Train.objects.filter(trainid=trainid)
x = a.values('trainid','trainnum','state','trainplace','starttime','trainname','traintype__dickeyname','teacher','submituser__name','submittime','trainlevel__dicname','traincontent__dickeyname','manlevel__dickeyname','detailcontent','participantnum','knownum','duration','material','pxxg','examtest__num','examtest__name')[0]
for key in x:
if x[key] == None:
x[key] = ''
x['material'] = x['material'].split('?')
str1=[]
for i in a.values('trainpart__partname'):
str1.append(i['trainpart__partname'])
x['trainpart']=','.join(str1)
str2=[]
for i in a.values('participant__name'):
str2.append(i['participant__name'])
x['participantname']=','.join(str2)
objs = Trainuser.objects.filter(train=a[0])
detailobjs = objs.order_by('checked').values('participant__name','participant__ubelongpart__partname','checked','qdsj','isnew')
x['dcsj'] = datetime.now()
x['cjrydetail'] = list(detailobjs)
#开始生成word
doc = DocxTemplate(dirname + "safesite/exportemp/px.docx")
doc.render(x)
filename = x['trainnum']
url = 'media/export/' + filename +'.docx'
filepath = dirname + url
doc.save(filepath)
return url
elif a=='yl':
drillid = id
a = Drill.objects.filter(drillid=drillid)
x = a.values('drillid','drillnum','state','drillplace','starttime','drilllevel__dicname','drillname','drilltype__dickeyname','commander','submituser__name','submittime','drillcontent__dickeyname','detailcontent','participantnum','knownum','material')[0]
for key in x:
if x[key] == None:
x[key] = ''
x['material'] = x['material'].split('?')
#对many字段单独处理
str1=[]
for i in a.values('drillpart__partname'):
str1.append(i['drillpart__partname'])
x['drillpart']=','.join(str1)
str2=[]
for i in a.values('participant__name'):
str2.append(i['participant__name'])
x['participantname']=','.join(str2)
x['dcsj'] = datetime.now()
#开始生成word
doc = DocxTemplate(dirname + "safesite/exportemp/yl.docx")
doc.render(x)
filename = x['drillnum']
url = 'media/export/' + filename +'.docx'
filepath = dirname + url
doc.save(filepath)
return url
elif a=='exampaper':
a = ExamPaper.objects.filter(id=id)
x = a.values('id','num','name','createtime','total')[0]
dxlist = []
duoxlist = []
pdlist = []
for i in ExamPaperDetail.objects.filter(exampaper__id=id):
if i.question.type==1:
dxlist.append({'title':i.question.title,'answer':i.question.answer,'score':i.score})
elif i.question.type==2:
duoxlist.append({'title':i.question.title,'answer':i.question.answer,'score':i.score})
elif i.question.type==3:
pdlist.append({'title':i.question.title,'answer':i.question.answer,'score':i.score})
x['questions'] = {'dx':dxlist,'duox':duoxlist,'pd':pdlist}
x['dcsj'] = datetime.now()
#开始生成word
doc = DocxTemplate(dirname + "safesite/exportemp/exampaper.docx")
doc.render(x)
filename = x['name']
output = BytesIO()
doc.save(output)
output.seek(0)
res = HttpResponse(content_type='application/msword')
res['Content-Disposition'] = 'attachment;filename='+filename+'.docx'
res.write(output.getvalue())
return res
elif a=='zy':
a = Operation.objects.filter(zyid=id)
x = a.values('zyid','zydd','zylx__dickeyname','zynum','zyfzr__name','zynr','zyzt','zyimg','submittime','zybm__partname','sdbm__partname','kssj','jssj','fxcs','zyimg2')[0]
x['zyimgs']=[]
x['zyimg2s']=[]
if x['zyimg']!='':
x['zyimg'] = x['zyimg'].split('?')
else:
x['zyimg']=[]
if x['zyimg2']!='':
x['zyimg2'] = x['zyimg2'].split('?')
else:
x['zyimg2']=[]
x['fxcs'] = list(Fxcs.objects.filter(id__in=x['fxcs'].split('?')).values('id','fxfx','aqcs','cslx'))
#确认详情
qrxq = Operzyry.objects.filter(oper=a[0]).values('operzyry__name','checked')
x['qrxq'] = list(qrxq)
#审批详情
spxq = Operspxq.objects.filter(oper=a[0]).order_by('submittime').values('jdmc','spbm__partname','spr__name','submittime','checked')
x['spxq'] = list(spxq)
x['dcsj'] = datetime.now()
#开始生成word
doc = DocxTemplate(dirname + "safesite/exportemp/zy.docx")
if x['zyimg']:
for i in x['zyimg']:
x['zyimgs'].append(InlineImage(doc,dirname + i,width=Mm(40)))
if x['zyimg2']:
for i in x['zyimg2']:
x['zyimg2s'].append(InlineImage(doc,dirname + i,width=Mm(40)))
doc.render(x)
filename = x['zynum']
output = BytesIO()
doc.save(output)
output.seek(0)
res = HttpResponse(content_type='application/msword')
res['Content-Disposition'] = 'attachment;filename='+filename+'.docx'
res.write(output.getvalue())
return res
elif a == 'jy':
a = Suggest.objects.filter(jyid=id)
x = a.values('jyid','jylb__dickeyname','jynum','submittime','jyr__name','dqxz','jynr','jybm__partname','jyimg','qwxg','jyqy__name','jydd','jyzt','clr__name','jyfk','clcs','pgr__name','clms','jyimg2','sjwcsj')[0]
if x['jyimg']!='':
x['jyimg'] = x['jyimg'].split('?')
else:
x['jyimg']=[]
for key in x:
if x[key] == None:
x[key] = ''
x['flow']=[]
for i in Suggestflow.objects.filter(suggest=a[0]).order_by('submittime'):
x['flow'].append({'name':i.user.name,'action':i.action,'submittime':i.submittime})
x['dcsj'] = datetime.now()
x['jyimgs']=[]
x['jyimg2s']=[]
#开始生成word
doc = DocxTemplate(dirname + "safesite/exportemp/jy.docx")
if x['jyimg']:
for i in x['jyimg']:
x['jyimgs'].append(InlineImage(doc,dirname + i,width=Mm(40)))
if x['jyimg2']:
for i in x['jyimg2']:
x['jyimg2s'].append(InlineImage(doc,dirname + i,width=Mm(40)))
doc.render(x)
filename = x['jynum']
output = BytesIO()
doc.save(output)
output.seek(0)
res = HttpResponse(content_type='application/msword')
res['Content-Disposition'] = 'attachment;filename='+filename+'.docx'
res.write(output.getvalue())
return res
elif a == 'ws':
a = Miss.objects.filter(missid=id)
x = a.values('missid','missnum','missqy__name','missplace','misstime','misser__name','description','prevent','misspart__partname','submittime','missimg','lesson')[0]
if x['missimg']:
x['missimg'] = x['missimg'].split('?')
else:
x['missimg']=[]
x['dcsj'] = datetime.now()
#开始生成word
x['missimgs'] = []
doc = DocxTemplate(dirname + "safesite/exportemp/ws.docx")
if x['missimg']:
for i in x['missimg']:
x['missimgs'].append(InlineImage(doc,dirname + i,width=Mm(60)))
doc.render(x)
filename = x['missnum']
output = BytesIO()
doc.save(output)
output.seek(0)
res = HttpResponse(content_type='application/msword')
res['Content-Disposition'] = 'attachment;filename='+filename+'.docx'
res.write(output.getvalue())
return res
import re
ILLEGAL_CHARACTERS_RE = re.compile(r'[\000-\010]|[\013-\014]|[\016-\037]')
def exportxlsx(a,objs):
if a =='yh':
wb = load_workbook(dirname + 'safesite/exportemp/yhdc.xlsx')
sheet = wb.active
#设置文字图片单元格的行高列宽
column_width = 15
row_height = 70
#查询数据
yhobjs = objs.order_by('-troubleid')
if yhobjs.count()>100:
res = HttpResponse()
res.write('数量超过100,请查询后导出!')
return res
vl = yhobjs.values('yhnum','fxr__name','yhms','yhzt','fxsj','tbsj','yhlb__dickeyname','yhpg__dickeyname','yhdd','fxbm__partname','yhdj__dickeyname','yhpg__dickeyname',
'jclx__dickeyname','yhlx__dicname','yyfx','zgcs','yhtp','zghtp','zgms','zgbm__partname','zgr__name','zgqx','shr__name','fcr__name')
vl=list(vl)
for i ,v in enumerate(vl):
v['yhzt']=yhobjs[i].get_yhzt_display()
if v['yhtp']:
v['yhtp']=v['yhtp'].split('?')
if v['zghtp']:
v['zghtp']=v['zghtp'].split('?')
# for key in vl[i]:
# if vl[i][key] == None:
# vl[i][key] = ''
#print(vl[i]['yhzt'],vl[i]['yhtp'])
#修改图片区列表宽度
sheet.column_dimensions['u'].width = column_width #修改列宽
sheet.column_dimensions['w'].width = column_width
#写入数据
for i ,v in enumerate(vl):
sheet.row_dimensions[i+4].height = row_height #修改行高
sheet['a'+str(i+4)] = v['yhzt']
sheet['b'+str(i+4)] = v['yhnum']
sheet['c'+str(i+4)] = v['yhdj__dickeyname']
sheet['d'+str(i+4)] = v['yhlx__dicname']
sheet['e'+str(i+4)] = v['yhlb__dickeyname']
sheet['f'+str(i+4)] = v['jclx__dickeyname']
sheet['g'+str(i+4)] = v['fxsj']
sheet['h'+str(i+4)] = ILLEGAL_CHARACTERS_RE.sub(r'', v['yhdd'])
sheet['i'+str(i+4)] = v['fxbm__partname']
sheet['j'+str(i+4)] = v['fxr__name']
sheet['k'+str(i+4)] = v['yhpg__dickeyname']
sheet['l'+str(i+4)] = ILLEGAL_CHARACTERS_RE.sub(r'', v['yhms'])
sheet['m'+str(i+4)] = v['zgbm__partname']
sheet['n'+str(i+4)] = v['zgr__name']
sheet['o'+str(i+4)] = v['zgqx']
sheet['p'+str(i+4)] = ILLEGAL_CHARACTERS_RE.sub(r'', v['yyfx'])
sheet['q'+str(i+4)] = ILLEGAL_CHARACTERS_RE.sub(r'', v['zgcs'])
sheet['r'+str(i+4)] = ILLEGAL_CHARACTERS_RE.sub(r'', v['zgms'])
sheet['s'+str(i+4)] = v['shr__name']
sheet['t'+str(i+4)] = v['fcr__name']
if v['yhtp']:
try:
img = Image(dirname + v['yhtp'][0])
if img.format!='mpo':
img.width, img.height = (90, 90) #这两个属性分别是对应添加图片的宽高
sheet.add_image(img, 'u'+str(i+4))
except:
pass
if v['zghtp']:
try:
img = Image(dirname + v['zghtp'][0])
if img.format!='mpo':
img.width, img.height = (90, 90) #这两个属性分别是对应添加图片的宽高
sheet.add_image(img, 'w'+str(i+4))
except:
pass
nowtime = datetime.now().strftime('%Y%m%d%H%M%S')
sheet['b1'] = nowtime
filename = 'YHS' + nowtime
output = BytesIO()
wb.save(output)
output.seek(0)
res = HttpResponse(content_type='application/vnd.ms-excel')
res['Content-Disposition'] = 'attachment;filename='+filename+'.xlsx'
res.write(output.getvalue())
return res
elif a=='px':
pxlist=[]
#查询数据
for train in objs:
a = Train.objects.filter(trainid=train.trainid)
x = a.values('trainid','trainnum','lecturer__name','state','trainplace','starttime','trainname','traintype__dickeyname','teacher','submituser__name','submittime','trainlevel__dicname','traincontent__dickeyname','manlevel__dickeyname','detailcontent','participantnum','knownum','duration')[0]
for key in x:
if x[key] == None:
x[key] = ''
str1=[]
for i in a.values('trainpart__partname'):
str1.append(i['trainpart__partname'])
x['trainpart']=','.join(str1)
str2=[]
for i in a.values('participant__name'):
str2.append(i['participant__name'])
x['participantname']=','.join(str2)
x['dcsj'] = datetime.now()
if x['state']==0:
x['state']=='未评估'
else:
x['state']=='已评估'
pxlist.append(x)
#写入数据
wb = load_workbook(dirname + 'safesite/exportemp/px.xlsx')
sheet = wb.active
for i in pxlist:
num = str(pxlist.index(i)+3)
sheet['a'+num] = i['state']
sheet['b'+num] = i['trainlevel__dicname']
sheet['c'+num] = i['traintype__dickeyname']
sheet['d'+num] = i['trainname']
sheet['e'+num] = i['manlevel__dickeyname']
sheet['f'+num] = i['starttime']
sheet['g'+num] = i['trainplace']
sheet['h'+num] = i['trainpart']
sheet['i'+num] = i['lecturer__name']
sheet['j'+num] = i['traincontent__dickeyname']
sheet['k'+num] = i['detailcontent']
sheet['l'+num] = i['participantname']
sheet['m'+num] = i['participantnum']
sheet['n'+num] = i['knownum']
sheet['o'+num] = i['submituser__name']
sheet['p'+num] = i['submittime']
sheet['q'+num] = i['duration']
nowtime = datetime.now().strftime('%Y%m%d%H%M%S')
sheet['b1'] = nowtime
filename = 'PXS' + nowtime
url = 'media/export/' + filename +'.xlsx'
filepath = dirname + url
wb.save(filepath)
return url
elif a=='yl':
yllist=[]
#查询数据
for drill in objs:
a = Drill.objects.filter(drillid=drill.drillid)
x = a.values('drillid','drillnum','state','drillplace','starttime','drilllevel__dicname','drillname','drilltype__dickeyname','commander','submituser__name','submittime','drillcontent__dickeyname','detailcontent','participantnum','knownum','material')[0]
for key in x:
if x[key] == None:
x[key] = ''
x['material'] = x['material'].split('?')
#对many字段单独处理
str1=[]
for i in a.values('drillpart__partname'):
str1.append(i['drillpart__partname'])
x['drillpart']=','.join(str1)
str2=[]
for i in a.values('participant__name'):
str2.append(i['participant__name'])
x['participantname']=','.join(str2)
x['dcsj'] = datetime.now()
if x['state']==0:
x['state']='未评估'
else:
x['state']='已评估'
yllist.append(x)
#写入数据
wb = load_workbook(dirname + 'safesite/exportemp/yl.xlsx')
sheet = wb.active
for i in yllist:
num = str(yllist.index(i)+3)
sheet['a'+num] = i['state']
sheet['b'+num] = i['drilllevel__dicname']
sheet['c'+num] = i['drilltype__dickeyname']
sheet['d'+num] = i['drillname']
sheet['e'+num] = i['starttime']
sheet['f'+num] = i['drillplace']
sheet['g'+num] = i['drillpart']
sheet['h'+num] = i['commander']
sheet['i'+num] = i['drillcontent__dickeyname']
sheet['j'+num] = i['detailcontent']
sheet['k'+num] = i['participantname']
sheet['l'+num] = i['participantnum']
sheet['m'+num] = i['knownum']
sheet['n'+num] = i['submituser__name']
sheet['o'+num] = i['submittime']
nowtime = datetime.now().strftime('%Y%m%d%H%M%S')
sheet['b1'] = nowtime
filename = 'YLS' + nowtime
url = 'media/export/' + filename +'.xlsx'
filepath = dirname + url
wb.save(filepath)
return url
elif a=='ws':
if objs.count()>100:
res = HttpResponse()
res.write('数量超过100,请查询后导出!')
return res
#查询数据
wslist = objs.values('missnum','missplace','misstime','misser__name','description','prevent','misspart__partname','submittime','missimg','lesson')
#写入数据
wb = load_workbook(dirname + 'safesite/exportemp/ws.xlsx')
sheet = wb.active
x=3
for i in wslist:
num = str(x)
i['missimg'] = i['missimg'].split('?')[0]
sheet['a'+num] = i['missnum']
sheet['b'+num] = i['missplace']
sheet['c'+num] = i['misstime']
sheet['d'+num] = i['misser__name']
sheet['e'+num] = i['misspart__partname']
sheet['f'+num] = i['description']
sheet['g'+num] = i['prevent']
sheet['h'+num] = i['lesson']
sheet['j'+num] = i['submittime']
if i['missimg']!='':
try:
img = Image(dirname + i['missimg'])
img.width, img.height = (90, 90) #这两个属性分别是对应添加图片的宽高
sheet.add_image(img, 'i'+num)
sheet.row_dimensions[x].height = 70
except:
pass
x = x + 1
nowtime = datetime.now().strftime('%Y%m%d%H%M%S')
sheet['b1'] = nowtime
filename = 'WSS' + nowtime
output = BytesIO()
wb.save(output)
output.seek(0)
res = HttpResponse(content_type='application/vnd.ms-excel')
res['Content-Disposition'] = 'attachment;filename='+filename+'.xlsx'
res.write(output.getvalue())
return res
elif a=='grpxjl':
#查询数据
wslist = objs.values('train__trainnum', 'train__trainid', 'train__state', 'train__trainplace', 'train__starttime', 'train__trainname',
'train__teacher', 'train__lecturer__name', 'participant__name', 'participant__name', 'checked', 'train__duration', 'examtestdetail')
#写入数据
wb = load_workbook(dirname + 'safesite/exportemp/grpxjl.xlsx')
sheet = wb.active
x=3
for i in wslist:
num = str(x)
sheet['a'+num] = i['participant__name']
sheet['b'+num] = i['train__trainnum']
if i['train__state']==0:
sheet['c'+num] = "待评估"
else:
sheet['c'+num] = "已评估"
sheet['d'+num] = i['train__trainname']
sheet['e'+num] = i['train__trainplace']
sheet['f'+num] = i['train__starttime']
sheet['g'+num] = i['train__duration']
if i['checked']==0:
sheet['h'+num] = "未微信签到"
else:
sheet['h'+num] = "已微信签到"
sheet['i'+num] = i['train__teacher']
x = x + 1
nowtime = datetime.now().strftime('%Y%m%d%H%M%S')
sheet['b1'] = nowtime
filename = 'WSS' + nowtime
output = BytesIO()
wb.save(output)
output.seek(0)
res = HttpResponse(content_type='application/vnd.ms-excel')
res['Content-Disposition'] = 'attachment;filename='+filename+'.xlsx'
res.write(output.getvalue())
return res
elif a=='jy':
if objs.count()>100:
res = HttpResponse()
res.write('数量超过100,请查询后导出!')
return res
#查询数据
jylist = objs.values('jynum','jylb__dickeyname','jyr__name','jybm__partname','dqxz','jynr','qwxg','submittime','jyimg','jyimg2','pgr__name','clr__name','jyfk','clcs','clms')
#写入数据
wb = load_workbook(dirname + 'safesite/exportemp/jy.xlsx')
sheet = wb.active
x=3
for i in jylist:
num = str(x)
i['jyimg'] = i['jyimg'].split('?')[0]
sheet['a'+num] = i['jynum']
sheet['b'+num] = i['jylb__dickeyname']
sheet['c'+num] = i['jyr__name']
sheet['d'+num] = i['jybm__partname']
sheet['e'+num] = i['dqxz']
sheet['f'+num] = i['jynr']
sheet['g'+num] = i['qwxg']
sheet['h'+num] = i['submittime']
sheet['i'+num] = i['pgr__name']
sheet['j'+num] = i['jyfk']
sheet['k'+num] = i['clr__name']
sheet['l'+num] = i['clcs']
sheet['m'+num] = i['clms']
if i['jyimg']!='':
try:
img = Image(dirname + i['jyimg'])
img.width, img.height = (90, 90) #这两个属性分别是对应添加图片的宽高
sheet.add_image(img, 'n'+num)
sheet.row_dimensions[x].height = 70
except:
pass
if i['jyimg2']:
i['jyimg2'] = i['jyimg2'][0]
try:
img = Image(dirname + i['jyimg2'])
img.width, img.height = (90, 90) #这两个属性分别是对应添加图片的宽高
sheet.add_image(img, 'o'+num)
sheet.row_dimensions[x].height = 70
except:
pass
x = x + 1
nowtime = datetime.now().strftime('%Y%m%d%H%M%S')
sheet['b1'] = nowtime
filename = 'JYS' + nowtime
output = BytesIO()
wb.save(output)
output.seek(0)
res = HttpResponse(content_type='application/vnd.ms-excel')
res['Content-Disposition'] = 'attachment;filename='+filename+'.xlsx'
res.write(output.getvalue())
return res
elif a=='gc':
if objs.count()>100:
res = HttpResponse()
res.write('数量超过100,请查询后导出!')
return res
#查询数据
gclist = objs.values('looknum','lookplace','actname','looktime','looktime2','looker__name','lookeder','otherunsafe','safecontent','lookpart__partname','submittime','lookimg')
#写入数据
output = BytesIO()
wb = xlsxwriter.Workbook(output, {'in_memory': True})
sheet = wb.add_worksheet()
bold = wb.add_format({'bold': 1})
sheet.write_row('A1',['编号','所属部门','观察人','开始时间','结束时间','地点','被观察人员','作业名称','过程和交流记录','共识和改进','提交时间','图片'],bold)
sheet.set_column(0,7,10)
sheet.set_column(8,9,30)
sheet.set_column(10,10,10)
sheet.set_column(11,11,60)
x=1
for i in gclist:
sheet.set_row(x, 60)
sheet.write(x,0,i['looknum'])
sheet.write(x,1,i['lookpart__partname'])
sheet.write(x,2,i['looker__name'])
sheet.write(x,3,i['looktime'].strftime("%Y-%m-%d %H:%M:%S"))
sheet.write(x,4,i['looktime2'].strftime("%Y-%m-%d %H:%M:%S") if i['looktime2'] else '')
sheet.write(x,5,i['lookplace'])
sheet.write(x,6,i['lookeder'])
sheet.write(x,7,i['actname'])
sheet.write(x,8,i['otherunsafe'])
sheet.write(x,9,i['safecontent'])
sheet.write(x,10,i['submittime'].strftime("%Y-%m-%d %H:%M:%S"))
i['lookimg']=i['lookimg'].split('?')
n = i['lookimg']
for m in n:
if m:
try:
img = PIL.Image.open(dirname+m)
sheet.insert_image(x,11, dirname+m, {'x_offset': 0 + n.index(m)*90, 'y_offset': 0,'x_scale': 80/(img.size)[0], 'y_scale': 80/(img.size)[1]})
except:
pass
x = x + 1
filename = 'GCS' + datetime.now().strftime('%Y%m%d%H%M%S')
wb.close()
output.seek(0)
res = HttpResponse(content_type='application/vnd.ms-excel')
res['Content-Disposition'] = 'attachment;filename='+filename+'.xlsx'
res.write(output.getvalue())
return res
elif a=='zy':
if objs.count()>100:
res = HttpResponse()
res.write('数量超过100,请查询后导出!')
return res
#查询数据
zylist = objs.values('zyid','zylx__dickeyname','zynum','zybm__partname','zyfzr__name','zynr','zyzt','submittime','kssj','jssj','zyimg','zyimg2')
wb = load_workbook(dirname + 'safesite/exportemp/zy.xlsx')
sheet = wb.active
x=3
for i in zylist:
num = str(x)
i['zyimg'] = i['zyimg'].split('?')[0]
i['zyimg2'] = i['zyimg2'].split('?')[0]
sheet['a'+num] = i['zynum']
sheet['b'+num] = i['zyzt']['zyzt']
sheet['c'+num] = i['zylx__dickeyname']
sheet['d'+num] = i['zynr']
sheet['e'+num] = i['zybm__partname']
sheet['f'+num] = i['zyfzr__name']
sheet['g'+num] = i['kssj']
sheet['h'+num] = i['jssj']
sheet['k'+num] = i['submittime']
if i['zyimg']!='':
try:
img = Image(dirname + i['zyimg'])
img.width, img.height = (90, 90) #这两个属性分别是对应添加图片的宽高
sheet.add_image(img, 'i'+num)
sheet.row_dimensions[x].height = 70
except:
pass
if i['zyimg2']!='':
try:
img = Image(dirname + i['zyimg2'])
img.width, img.height = (90, 90) #这两个属性分别是对应添加图片的宽高
sheet.add_image(img, 'i'+num)
sheet.row_dimensions[x].height = 70
except:
pass
x = x + 1
nowtime = datetime.now().strftime('%Y%m%d%H%M%S')
sheet['b1'] = nowtime
filename = 'ZYS' + nowtime
output = BytesIO()
wb.save(output)
output.seek(0)
res = HttpResponse(content_type='application/vnd.ms-excel')
res['Content-Disposition'] = 'attachment;filename='+filename+'.xlsx'
res.write(output.getvalue())
return res
elif a == 'xj':#巡检记录
#查询数据
xjlist = objs.values('id','state','content','creattime','equipment__num','equipment__name','equipment__area__name','user__name','user__ubelongpart__partname','trouble__yhzt','trouble__yhnum','trouble__yhms')
wb = load_workbook(dirname + 'safesite/exportemp/xj.xlsx')
sheet = wb.active
x=3
for i in xjlist:
num = str(x)
sheet['a'+num] = i['user__ubelongpart__partname']
sheet['b'+num] = i['user__name']
sheet['c'+num] = i['equipment__num']
sheet['d'+num] = i['equipment__name']
sheet['e'+num] = i['equipment__area__name']
sheet['f'+num] = i['state']
sheet['g'+num] = i['content']
sheet['h'+num] = i['trouble__yhnum']
sheet['i'+num] = i['creattime']
x = x + 1
nowtime = datetime.now().strftime('%Y%m%d%H%M%S')
sheet['b1'] = nowtime
filename = 'XJS' + nowtime
output = BytesIO()
wb.save(output)
output.seek(0)
res = HttpResponse(content_type='application/vnd.ms-excel')
res['Content-Disposition'] = 'attachment;filename='+filename+'.xlsx'
res.write(output.getvalue())
return res
elif a == 'equipment':#设备
#查询数据
wb = load_workbook(dirname + 'safesite/exportemp/equipment.xlsx')
sheet = wb.active
for i, x in enumerate(objs):
num = str(i+3)
sheet['a'+num] = x.num
sheet['b'+num] = x.name
if x.cate:
sheet['c'+num] = x.cate.dickeyname
sheet['d'+num] = x.type
if x.area:
sheet['e'+num] = x.area.name
sheet['f'+num] = '正常' if x.state==1 else '异常'
sheet['g'+num] = 'https://safeyun.ctcshe.com/miniprogram/equipment?id='+str(x.id)
nowtime = datetime.now().strftime('%Y%m%d%H%M%S')
sheet['b1'] = nowtime
filename = 'SBS' + nowtime
output = BytesIO()
wb.save(output)
output.seek(0)
res = HttpResponse(content_type='application/vnd.ms-excel')
res['Content-Disposition'] = 'attachment;filename='+filename+'.xlsx'
res.write(output.getvalue())
return res
def exportyjdoc(vl):
doc = DocxTemplate(dirname + "safesite/exportemp/fxbg.docx")
#整理数据
vl['now']=datetime.now().strftime('%Y-%m-%d %H:%M')
companyname = vl['companyname']
year = vl['year']
month = vl['month']
for i in range(7):
imgpath = dirname +'media/export/chart/'+companyname+year+'-'+month+'-'+str(i+1)+'.png'
#txtpath = dirname +'media/export/chart/'+companyname+year+'-'+month+'-'+str(i+1)+'.txt'
pnginfo = vl['map'+str(i+1)+'v']
pnginfo.replace(" ", "+") #获得base64的坑,用加号替代空格
#pnginfo.replace(r'data:image/png;base64,','') #移除头部
pnginfo = tran64(pnginfo[22:]) #又一个坑
#with open(txtpath,'w') as f:
#f.write(pnginfo)
with open(imgpath,'wb') as f:
f.write(base64.b64decode(pnginfo)) #写入图片
if i==0:
vl['map'+str(i+1)+'v']=InlineImage(doc,imgpath,width=Mm(60))
else:
vl['map'+str(i+1)+'v']=InlineImage(doc,imgpath,width=Mm(120))
#开始生成分析报告
doc.render(vl)
filename = companyname+year+'-'+month+'.docx'
url = 'media/export/' + filename
filepath = dirname + url
doc.save(filepath)
return url
def tran64(s):
missing_padding = len(s) % 4
if missing_padding != 0:
s = s+'='* (4 - missing_padding)
return s
def exportsimplexlsx(datalist):
pass