Python比較兩個excel文檔內容的異同

#-*- coding: utf-8 -*-#比對兩個Excel文件內容的差別#---------------------假設條件----------------#一、源表和目標表格式一致#二、不存在合併單元格#三、第2行開始比對#---------------------------------------------import xlrdimport xlwtimport osimport time;  # 引入time模塊#往日誌文件中追加內容函數def writeappend_logfile(filename,content):    file=open(filename,'a') #以追加方式打開日誌文件    time_now= time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())  #系統時間格式化    file.writelines(time_now+':'+content+'\n')      #寫入內容    file.close() #關閉文件def read_excel(ori_path,tar_path,sub_name):#    #print("ori_path:", ori_path)    #print("tar_path:", tar_path)    success=0        #匹配一致數量    fail=0           #匹配不一致數量    origin_xls={} #存儲源xls文件    target_xls={} #比對的xls文件    wb_ori=xlrd.open_workbook(ori_path) #打開原始文件    wb_tar=xlrd.open_workbook(tar_path) #打開目標文件    sheet_num = len(wb_ori.sheets()) #源表子表數量##    for sheet_i in range(sheet_num):  #excel中子頁面數量##        sheet_ori=wb_ori.sheet_by_index(sheet_i) #經過索引值獲取源表名##        sheet_tar=wb_tar.sheet_by_index(sheet_i) #經過索引值獲取源表名    startime=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())    #獲取系統當前時間並格式化爲格式    print (startime,' 開始比對...')    logname='log_'+startime[0:10]+'.log'               #截取日期年月日構成日誌文件名    logfile=open(logname,'w')    #建立日誌文件,若是文件存在則清空內容,不存在則建立,若是須要同時批量比對多張表,能夠考慮將日誌文件名做爲參數傳入    logfile.writelines(startime+':【開始比對】...'+'\n')       #寫入開始時間    logfile.close()            #關閉日誌文件    #print("##########################")    try:        sheet_ori=wb_ori.sheet_by_name(sub_name)        #print("sheet_ori.name:", sheet_ori.name)        sheet_tar=wb_tar.sheet_by_name(sub_name)        #print("sheet_tar.name:", sheet_tar.name)        #print("1111111111111111111111111111111")        if sheet_ori.name==sheet_tar.name:            #sheet表名            if sheet_ori.name==sub_name:            #先將數存入dictionary中dictionary(rows:list)            #第一行存儲表頭            #源表取一行數據與目標表全表進行比對若是表中存在主鍵能夠用主鍵進行索引            #數據從excel第3行開始                #print("222222222222222222222222222")                for rows in range(0,sheet_ori.nrows):                    orign_list=sheet_ori.row_values(rows) #源表i行數據                    #target_list=sheet_tar.row_values(rows) #目標表i行數據                    origin_xls[rows]=orign_list     #源表寫入字典                    #print("origin_xls[rows]:", origin_xls[rows])                    #target_xls[rows]=target_list    #目標表寫入字典                for rows in range(0, sheet_tar.nrows):                    target_list = sheet_tar.row_values(rows)  # 目標表i行數據                    target_xls[rows] = target_list  # 目標表寫入字典                    #print("target_xls[rows]", target_xls[rows])                if origin_xls[0]  == target_xls[0]:                    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+' 表頭一致')                num = len(origin_xls)                print("num:", num)                num1 = len(target_xls)                print("num1:", num1)                if num >= num1:                    for ori_num in origin_xls:                        print("ori_num:", ori_num)                        flag='false'          #判斷是否一致標誌                        for tar_num in target_xls:                            if origin_xls[ori_num]==target_xls[tar_num]:                                flag='true'                                break              #若是匹配到結果退出循環                        if flag=='true':           #匹配上結果輸出後臺日誌                            print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+' 文件:', ori_path+' '+' row:%d is ok'%(ori_num+1))                            success+=1                        else:                      #匹配不上將源表中行記錄寫入txt                            print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+' 文件:', ori_path+' '+' row:%d is different'%(ori_num+1))                            fail+=1                            data=origin_xls[ori_num]                            logstr='文件:', ori_path + ' ' + '【不一致】row<'+str(ori_num)+'>:'+str(data)                            writeappend_logfile(logname,logstr)                    # logstr='【比對完成】總記錄數:'+str(ori_num)+'條,一致:'+str(success)+'條,不一致:'+str(fail)+'條'                    logstr='【比對完成】總記錄數:{:d}條,一致:{:d}條,不一致:{:d}條'.format(ori_num + 1,success,fail)                    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+' 【%s】比對結束'%sheet_ori.name)                    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+' 總記錄數:%d條,一致:%d條,不一致:%d條'%(ori_num+1,success,fail))                    writeappend_logfile(logname,logstr)                else:                    for tar_num in target_xls:                    #for ori_num in origin_xls:                        #print("tar_num:", tar_num)                        flag = 'false'  # 判斷是否一致標誌                        #for tar_num in target_xls:                        for ori_num in origin_xls:                            #if origin_xls[ori_num] == target_xls[tar_num]:                            if target_xls[tar_num] == origin_xls[ori_num]:                                flag = 'true'                                break  # 若是匹配到結果退出循環                        if flag == 'true':  # 匹配上結果輸出後臺日誌                            print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' 文件: ', tar_path+' '+ ' row:%d is ok' % (tar_num + 1))                            success += 1                        else:  # 匹配不上將源表中行記錄寫入txt                            print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+ ' 文件: ', tar_path+' ' + ' row:%d is different' % (                                    tar_num + 1))                            fail += 1                            data = target_xls[tar_num]                            #logstr = '文件: ', tar_path + ' ' + '【不一致】row<' + str(tar_num+1) + '>:' + str(data)                            logstr = '【不一致】row<' + str(tar_num + 1) + '>:' + str(data)                            #logstr1 = ' 文件: ', tar_path                            #logstr =  logstr2 + logstr1                            writeappend_logfile(logname, logstr)                    # logstr='【比對完成】總記錄數:'+str(ori_num)+'條,一致:'+str(success)+'條,不一致:'+str(fail)+'條'                    logstr = '【比對完成】總記錄數:{:d}條,一致:{:d}條,不一致:{:d}條'.format(tar_num + 1, success, fail)                    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' 【%s】比對結束' % sheet_tar.name)                    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) + ' 總記錄數:%d條,一致:%d條,不一致:%d條' % (                    tar_num + 1, success, fail))                    writeappend_logfile(logname, logstr)        else:            errmsg='【'+sub_name+'】子表名不一致'            writeappend_logfile(logname,errmsg)    except Exception as err:       writeappend_logfile(logname,str(err)) #輸出異常def main():    passif __name__ == '__main__':    read_excel(r'1.xlsx','2.xlsx','Sheet1')
相關文章
相關標籤/搜索