import os
import sys
import struct
import binascii
import xlwt
def ParseData(parsebytes):
i=0
j=1
data_len=len(parsebytes)
while(i<data_len-1):
try:
send_flag=struct.unpack('b',parsebytes[i+2:i+3])[0]
pint_id=struct.unpack('<H',parsebytes[i+3:i+5])[0]
dev_id=struct.unpack('<H',parsebytes[i+5:i+7])[0]
order=struct.unpack('<I',parsebytes[i+7:i+11])[0]
cur_time=struct.unpack('<I',parsebytes[i+11:i+15])[0]
cur_data=struct.unpack('<I',parsebytes[i+39:i+43])[0]
#寫入excel表格進行后續分析
sheet.write(j, 0, send_flag)
sheet.write(j, 1, pint_id)
sheet.write(j, 2, dev_id)
sheet.write(j, 3, order)
sheet.write(j, 4, cur_time)
sheet.write(j, 5, cur_data)
except:
print('memory is overflow')
finally:
i=i+47
j=j+1
#切換到指定目錄
os.chdir(r'C:\Users\Usmart\Desktop\file_test')
#創建excel表格
book=xlwt.Workbook(encoding="utf-8",style_compression=0)
sheet = book.add_sheet('表1', cell_overwrite_ok=True) #cell_overwrite_ok,表示是否可以覆蓋單元格
sheet.write(0, 0, '發送標志')
sheet.write(0, 1, '采集點ID')
sheet.write(0, 2, '設備ID')
sheet.write(0, 3, '流水號')
sheet.write(0, 4, '采集時間')
sheet.write(0, 5, '設備數據')
#讀取歷史數據的二進制文件進行解析
fp=open("history.dat",'rb')
filedata = fp.read()
ParseData(filedata)
print('Auto test finish')
fp.close()
#保存並生成excel文件
book.save('歷史統計.xls')