Python3 implementing two Excel file content pairs

Source: Internet
Author: User

Recently in the work, need to manually than a large number of Excel format report, just learned the basic knowledge of Pyhon primer, think of writing something to practice practiced hand, not only can improve the code writing ability, but also can reduce workload, improve work efficiency. Just do it, simple logic. First, the contents of the target table and the source table are written to the dictionary, and the Excel table is not sure if there are any fields that are unique values, so the row number is selected as the key value, the contents of a row are placed in the list, and then a row is traversed from the source table to the target table. Think well after the start of the code, in the code writing process encountered a lot of problems, are encountered a check one. After the basic comparison function is implemented, it is thought to compare the results with the added log records. Write down this document, just do it.
Here's all the code

#-*-coding:utf-8-*-#比对两个Excel文件内容的差异 #---------------------Assumptions----------------#1, source table and target table-consistent # #, no merged cells  The 2nd line starts to compare to #---------------------------------------------import Xlrdimport xlwtimport osimport time; # Introducing the time module # Add content function def writeappend_logfile (filename,content): File=open (filename, ' a ') #以追加方式打开日志文件 time_now= Tim E.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()) #系统时间格式化 file.writelines (time_now+ ': ' +content+ ' \ n ') #写入内容 fi Le.close () #关闭文件def read_excel (ori_path,tar_path,sub_name): # success=0 #匹配一致数量 fail=0 #匹配不一致数量 o rigin_xls={} #存储源xls文件 target_xls={} #比对的xls文件 wb_ori=xlrd.open_workbook (ori_path) #打开原始文件 wb_tar=xlrd.open_workb        Ook (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, ' start compared to ... ') logname= ' Log_ ' +startime[0:10]+ '. Log ' #截取日期年月日构成日志文件名 Logfile=open (logname, ' W ') #创建日志文件, if the file exists then empties the content, does not exist, and if you need to batch multiple tables simultaneously, consider passing the log file name as a parameter to the Logfile.writelines (startime+ ': ' Start to compare ' ... ' + ' \ n ') #写入开始时间 logfile.close () #关闭日志文件 try:sheet_ori=wb_ori.sheet_by_name (sub_n            AME) 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) #第一行存储表头 #源表取一行数据                    Compare to the target table full table if a primary key exists in the table, the primary key can be indexed #数据从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 ()) + ' table header consistent ') fo                        R 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= ' "Inconsistent" row< ' +str (ori_num) + ';: ' +str (data) Writeappen D_logfile (logname,logstr# logstr= ' "Compared to complete" total Records: ' +str (ori_num) + ' bar, consistent: ' +str (Success) + ', Inconsistent: ' +str (fail) + ' ' logstr= ' "alignment Complete Total records: {:d}, consistent: {:D}, inconsistent: {:d} bar '. Format (ori_num,success,fail) print (Time.strftime ("%y-%m-%d%h:%m:%s", Tim E.localtime ()) + '%s ' End of '%sheet_ori.name ' Print (Time.strftime ("%y-%m-%d%h:%m:%s", Time.localtime ()) + ' total record ' Number:%d, consistent:%d, inconsistent:%d '% (ori_num,success,fail)) Writeappend_logfile (LOGNAME,LOGSTR) else:e Rrmsg= ' "' +sub_name+ '" sub-table name inconsistent ' Writeappend_logfile (logname,errmsg) except Exception as Err:writeappend_ LogFile (LOGNAME,STR (ERR)) #输出异常def main (): passif __name__ = = ' __main__ ': Read_excel (R ' 2.xls ', 1.xls ', ' Sheet1 ')

Python3 to implement two Excel file content pairs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.