1. 程式人生 > >Python3實現兩個Excel文件內容比對

Python3實現兩個Excel文件內容比對

都是 格式 lines 當前 msg 不存在 pyhon [1] 練手

最近在工作中,需要人工比對大量的excel格式報表,剛好剛學了Pyhon入門基礎知識,想著寫個東西練練手,不但能提高代碼編寫能力,還能減輕工作量,提高工作效率。說幹就幹,簡單的理了邏輯。首先,將目標表和源表的內容分別寫入到字典中,Excel表中不確定有沒有字段是唯一值,所以選擇了行號作為key值,一行的內容放到list中,然後從源表中取一行去目標表中遍歷。想好之後開始敲代碼了,在代碼編寫過程中遇到很多的問題,都是遇到一個查一個。基本的比對功能實現後,就想著在加個日誌記錄下比對結果。寫下此文記錄下,just do it.
下面是全部代碼

#-*- coding: utf-8 -*-

#比對兩個Excel文件內容的差異
#---------------------假設條件----------------
#1、源表和目標表格式一致
#2、不存在合並單元格
#3、第2行開始比對
#---------------------------------------------

import xlrd
import xlwt
import os
import 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):#
    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()            #關閉日誌文件

    try:
        sheet_ori=wb_ori.sheet_by_name(sub_name)
        sheet_tar=wb_tar.sheet_by_name(sub_name)
        if sheet_ori.name==sheet_tar.name:
            #sheet表名
            if sheet_ori.name==sub_name:
            #先將數存入dictionary中dictionary(rows:list)
            #第一行存儲表頭
            #源表取一行數據與目標表全表進行比對如果表中存在主鍵可以用主鍵進行索引
            #數據從excel第3行開始
                for rows in range(1,sheet_ori.nrows):
                    orign_list=sheet_ori.row_values(rows) #源表i行數據
                    target_list=sheet_tar.row_values(rows) #目標表i行數據
                    origin_xls[rows]=orign_list     #源表寫入字典
                    target_xls[rows]=target_list    #目標表寫入字典

                if origin_xls[1]  == target_xls[1]:
                    print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+‘ 表頭一致‘)
                for ori_num in origin_xls:
                    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())+‘ row:%d is ok‘%ori_num)
                        success+=1
                    else:                      #匹配不上將源表中行記錄寫入txt
                        print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())+‘ row:%d is different‘%ori_num)
                        fail+=1
                        data=origin_xls[ori_num]
                        logstr=‘【不一致】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,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,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():
    pass

if __name__ == ‘__main__‘:

    read_excel(r‘2.xls‘,1.xls‘,‘sheet1‘)

Python3實現兩個Excel文件內容比對