今天做项目时要求完成一个巡更过程,并能够导出巡更的时间地点信息。在此做一个笔记。。
前台使用Extjs框架,具体代码如下
1. 页面的布局如下
new Ext.Viewport({
enableTabScroll:true,
layout:"border",
items:[{
region:"north",
height:64,
items:[panel]//整个系统的导航栏由js引入
},{
region:'west',
width:document.body.clientWidth*0.3,
layout:'fit',
items:[treepanel]//左边为此系统的用户列表
},{
region : 'center',
collapsible : true,
layout : 'fit',
items:[pathgrid]//中间为某用户的巡更报表信息
}]
});
var treepanel = new Ext.ux.tree.ColumnTree({
rootVisible:false,
autoScroll:true,
width:document.body.clientWidth*0.3, height:document.documentElement.clientHeight,//不加高则不会显示滚动条
border:false,
title:'用户列表' ,
columns:[{
header:'分中心名',
width:150,
dataIndex:'groupname'
},{
header:'用户名',
width:100,
dataIndex:'username'
}],
loader:new Ext.tree.TreeLoader({
dataUrl:'/control/treegridsource/',//从服务器异步加载用户数据
uiProviders:{
'col':Ext.ux.tree.ColumnNodeUI
}
}),
root:new Ext.tree.AsyncTreeNode({
text:'root',
id:'rootid'
})
});
treepanel.on('click',function(node){
if(!node.hasChildNodes()){
selectusrid=node.id;
winHistory.show();
} //点击用户列表的用户可以显示时间选择框,用户生成该用户的巡更报表
});
var selectusrid;
var starttime;
var endtime;
function getdatetime(){//获得当前的时刻
var now = new Date;
var year = now.getYear();
var month= now.getMonth()+1;
var day=now.getDate();
var hour=now.getHours();
var minute=now.getMinutes();
if(month<10){
month="0"+month
}
if(day<10){
day='0'+day
}
if(hour<10){
hour='0'+hour
}
if(minute<10){
minute='0'+minute
}
return year+"-"+month+"-"+day+" "+hour+":"+minute;
//return year+'-'+month+'-'+day
};
function getdatetimepermon(){//获得当前时间的前一个小时时刻
var now = new Date();
var year = now.getYear();
var month= now.getMonth();
var day=now.getDate();
var hour=now.getHours();
var minute=now.getMinutes();
if(month<10){
month="0"+month
}
if(day<10){
day='0'+day
}
if(minute<10){
minute='0'+minute
}
return year+"-"+month+"-"+day+" "+hour+":"+minute;
//return year+'-'+month+'-'+day
};
//以上两个函数作为时间选择窗口的默认时间
var startdate = new Cls.form.DateTimeField({
fieldLabel:'起始时间',
emptyText:getdatetimepermon(),
name:'starttime',
anchor:'95%',
id:'startdt',
format:'Y-m-d H:i',
endDateField:'enddt'//要对应下面enddate的id
})
var enddate = new Cls.form.DateTimeField({
fieldLabel:'结束时间',
name:'endtime',
emptyText:getdatetime(),
anchor:'95%',
id:'enddt',
format:'Y-m-d H:i',
startDateField:'startdt'//要对应上面startdata的id
})
var timePanel = new Ext.form.FormPanel({
labelAlign:'left',
labelWidth:60,
width:270,
height:100,
frame:true,
bodyStyle:'padding:5px 5px 0',
items:[startdate,enddate]
})
var winHistory=new Ext.Window({
title:"时间段设置",
id:'winHistory',
closable:false,
width:270,
height:150,
buttonAlign:'center',
items:[timePanel],
resizable:false, //是否拉大窗口大小
modal:true, //窗口背面遮罩显示
buttons:[{
text:'确定',
handler: function(){
pathstore.removeAll()
starttime=Ext.get("startdt").dom.value;
endtime = Ext.get('enddt').dom.value;
pathstore.load({params:{userid:selectusrid,start:0,limit:myPageSize,starttime:starttime,endtime:endtime}});//向服务器传递参数放回巡更的时间和地点信息
winHistory.hide();
}
},{
text:'重置',
handler:function(){
timePanel.getForm().reset();
}
},{
text:'取消',
handler:function(){
winHistory.hide()
}
}]
})
var pathReader=new Ext.data.JsonReader({
totalProperty:'total',
root:'path',
fields:[{
name:'usr_name'
},{
name:'time'
},{
name:'point_name'
}]
},null)//name 要与后台返回的json字段对应
var pathstore= new Ext.data.Store({
remoteSort:true,
reader:pathReader,
proxy:new Ext.data.HttpProxy({
url:'/control/pathsource/',
timeout: 1000000
})
})
var pathCm=new Ext.grid.ColumnModel([
new Ext.grid.RowNumberer(),
{
header:'用户名',width:120,dataIndex:'usr_name'
}, {
header:'时间',width:120,dataIndex:'time'
},{
header:'巡更点',width:120,dataIndex:'point_name'
}])//dataIndex应该与pathCm中的dataIndex字段对应
var pathgrid= new Ext.grid.GridPanel({
id:'pathgrid',
loadMask:'loading...',
cm:pathCm,
store:pathstore,
striprRows:true,
border : false,
viewConfig:{
autoScroll:true
},
bbar:new Ext.PagingToolbar({
store:pathstore,
displayInfo:true,
displayMsg:'显示{0}条到{1}条记录,共{2}条',
pageSize:myPageSize,
emptyMsg:'没有记录',
items:[{
'text':'导出路线报表',
handler:function(){
var form=$(");//定义一个form表单
form.attr("style","display:none");
form.attr("target","");
form.attr("method","post");
form.attr("action","/control/showexcel/");
var input0=$("");
input0.attr("type","hidden");
input0.attr("name","userid");
input0.attr("value",selectusrid);
var input1=$("");
input1.attr("type","hidden");
input1.attr("name","starttime");
input1.attr("value",starttime);
var input2=$("");
input2.attr("type","hidden");
input2.attr("name","endtime");
input2.attr("value",endtime);
$("body").append(form);//将表单放置在web中
//3个input中的name和value是需要向后台传递的参数
form.append(input0);
form.append(input1);
form.append(input2);
form.submit();//表单提交
}
}]
//prependButtons:true,
})
})
前面页面显示如下
点击导出路线报表即可生成Excel表格
7. 此页面共3次请求后台,后台有django框架实现
1)请求用户列表代码'/control/treegridsource/'
def treegridsource1(request):
unitlist=[]
relatedusers=[]
treelist=[]
relateddevs = []
oneuserdict={}
nodeid = request.POST.get('node','')
uname = request.session.get('uname','null')
logging.info(uname)
userpk=Users.objects.filter(name = uname)[0].userid
# usergroupid=UserGroupPrivs.objects.filter(userid=userpk)[0].groupid
#groupname=Group.objects.filter(group_id=usergroupid)[0].group_name
#users=Users.objects.filter(name__startswith='PNUT')
users=UserUserPrivs.objects.filter(user1_id=userpk)
logging.info(users)
groups=UserGroupPrivs.objects.filter(userid=userpk)
logging.info(groups)
for i in groups:
groupid=i.groupid
unitlist.append(str(groupid))
unitlist=list(set(unitlist))
unitlen=len(unitlist)
if nodeid == 'rootid':
treelist = []
x=0
while x < unitlen:
onegroupdict = {'id':str(unitlist[x]),'groupname':Group.objects.filter(group_id=unitlist[x])[0].group_name,'usernme':'','usernum:':'','utctime':'skip','uiProvider':'col','icon':'/static/buttons/home_32.png'}
treelist.append(onegroupdict)
x = x+1
for index in range(unitlen):
if nodeid == str(unitlist[index]):
treelist =[]
useridlists=UserGroupPrivs.objects.filter(groupid=nodeid)
for one in users:
for j in useridlists:
if one.user2_id==j.userid:
nowutc=time.time()
lastactive=Users.objects.filter(userid=one.user2_id)[0].lastactive
if nowutc-lastactive<300:
last='TRUE'
else:
last='FALSE'
oneuserdict = {'id':one.user2_id,'groupname':'','username':Users.objects.filter(userid=one.user2_id)[0].name,'utctime':last,'uiProvider':'col','leaf':True,'icon':'/static/buttons/mobile.png','phone_num':Users.objects.filter(userid=one.user2_id)[0].phone_num}
treelist.append(oneuserdict)
data = '%s' %(simplejson.dumps(treelist,ensure_ascii = False))
print 'debugpoint'
return HttpResponse(data,mimetype='text/javascript;')
2)请求巡更信息的代码'/control/pathsource/'
def pathsource(request):
routelist=[]
user_id=request.POST.get('userid','')
start= request.POST.get('start','')
limit=request.POST.get('limit','')
starttime=request.POST.get('starttime','')
endtime=request.POST.get('endtime','')
if starttime!='' and endtime!='':
request.session['starttime']=starttime
request.session['endtime']=endtime
elif starttime=='' and endtime=='':
starttime=request.session['starttime']
endtime=request.session['endtime']
starttime=starttime+ ':00'
endtime=endtime+ ':00'
start1=time.strptime(starttime,'%Y-%m-%d %H:%M:%S')
end1 =time.strptime(endtime,'%Y-%m-%d %H:%M:%S')
utc_8=28800
utc_start = int(time.mktime(start1))
utc_end = int(time.mktime(end1))
start = int(start)
limit = int(limit)
print '22222'
routes=UserGpsInfo.objects.filter(userid=user_id,gpsutc__gte=utc_start,gpsutc__lte=utc_end).order_by('gpsutc')
length=len(routes)
print length
for obj in routes:
usrname=Users.objects.get(userid=obj.userid).name
point_name=PresetPointInfo.objects.get(id=obj.pointid).point_name
get_gpsutc=time.gmtime(obj.gpsutc)
get_gpsutc_str="%d/%d/%d %02d:%02d:%02d" %(get_gpsutc.tm_year,get_gpsutc.tm_mon,get_gpsutc.tm_mday,get_gpsutc.tm_hour,get_gpsutc.tm_min,get_gpsutc.tm_sec)
c={'usr_name':usrname,'time':get_gpsutc_str,'point_name':point_name}
routelist.append(c)
routeslice=routelist[start:start+limit]
print routeslice
data='{"total":%s,%s:%s}' % (length,'path',simplejson.dumps(routeslice,ensure_ascii=False))
return HttpResponse(data,mimetype='text/javascript;')
3)请求导出Excel报表的后台代码"/control/showexcel/"
def showexcel(request):
user_id=request.POST.get('userid','')
logging.info(user_id)
starttime=request.POST.get('starttime','')
endtime=request.POST.get('endtime','')
starttime=starttime+ ':00'
endtime=endtime+ ':00'
start=time.strptime(starttime,'%Y-%m-%d %H:%M:%S')
end =time.strptime(endtime,'%Y-%m-%d %H:%M:%S')
logging.info(starttime+'------------------'+endtime)
utc_8=28800
utc_start = int(time.mktime(start))
utc_end = int(time.mktime(end)) routes=UserGpsInfo.objects.filter(userid=user_id,gpsutc__gte=utc_start,gpsutc__lte=utc_end).order_by('gpsutc')
logging.info(len(routes))
w=Workbook(encoding='utf-8')
wd=w.add_sheet('基础表格')
fnt=Font()
fnt.name='Arial'
fnt.bold=True
fnt.height =20*16
borders=Borders()
borders.left=1
borders.right=1
borders.top=1
borders.bottom=1
al=Alignment()
al.horz=Alignment.HORZ_CENTER
al.vert=Alignment.VERT_CENTER
style=XFStyle()
style.font=fnt
style.alignment=al
fnt1=Font()
fnt1.name='Times New Roman'
fnt1.height=20*7
fnt1.bold=False
style1=XFStyle()
style1.borders=borders
style1.alignment=al
style1.fnt=fnt1
wd.write_merge(0,0,0,2,'巡更记录表',style)
wd.write_merge(1,3,0,0,'用户名',style1)
wd.write_merge(1,3,1,1,'巡更时间',style1)
wd.write_merge(1,3,2,2,'巡更地点',style1)
i=4
for obj in routes:
usrname=Users.objects.get(userid=obj.userid).name
point_name=PresetPointInfo.objects.get(id=obj.pointid).point_name
get_gpsutc=time.gmtime(obj.gpsutc)
get_gpsutc_str="%d/%d/%d %02d:%02d:%02d" %(get_gpsutc.tm_year,get_gpsutc.tm_mon,get_gpsutc.tm_mday,get_gpsutc.tm_hour,get_gpsutc.tm_min,get_gpsutc.tm_sec)
wd.write(i,0,usrname)#将从数据库中取出的信息写入表格中
wd.write(i,1,get_gpsutc_str)
wd.write(i,2,point_name)
wd.col(0).width=6666#设置表的宽度
wd.col(1).width=6666
wd.col(2).width=6666
i=i+1
#w.save('text.xls')
response = HttpResponse(mimetype='application/ms-excel')
response['Content-Disposition'] = 'attachment;filename=traffic[%s-%s].xls'%(starttime,endtime)
w.save(response)
return response