需要比较来自两个不同工作簿的测试用例,如果它们匹配,则将同一行的其他列中的结果与新工作簿进行比较

时间:2016-01-20 13:34:07

标签: python excel compare xlrd xlwt

我在编写这个东西时遇到困难。我有两张带有类似工作表的excel工作簿。这些工作表包含测试用例,其中一个可能有比另一个更多的测试用例。我试图将匹配测试用例的结果(可以在不同的列中提供)取出到新文件(最好是excel)。接下来,我必须列出另一个工作表中不存在的测试用例。

import xlrd
import xlwt
m=-1
new=[]
#hard coding of default values
WB1= xlrd.open_workbook("WB1.xls")
WB2= xlrd.open_workbook("WB2.xls")
wb_output = xlwt.Workbook()
ws = wb_output.add_sheet('Comparison_sheet')
WB1_Sheet= WB1.sheet_by_index(1)
WB2_Sheet= WB2.sheet_by_index(1)
if WB1_Sheet.nrows > WB2_Sheet.nrows:
    Last_row=WB2_Sheet.nrows
else:
    Last_row=WB1_Sheet.nrows

if WB1_Sheet.ncols > WB2_Sheet.ncols:
    Last_Column=WB2_Sheet.ncols
else:
    Last_Column=WB1_Sheet.ncols
for x in range(24,Last_row):
    for counter in range(0,30):
        #checking matching test cases in next 20 test cases 
        y=x+counter
        if x>Last_row or y>Last_row:
            y=y-counter
            break;
        if WB2_Sheet.cell_value(x,0) == WB1_Sheet.cell_value(y,0):
            found=1;
            m+=1
            ws.write(m, 0,(str(x +1)))
            ws.write(m, 1,(str(WB1_Sheet.cell_value(x,0)) + "\n" +str(WB2_Sheet.cell_value(y,0))))
            ws.write(m, 2,(str(WB2_Sheet.cell_value(x,3))))
            ws.write(m, 3,(str(WB1_Sheet.cell_value(y,3))))
        if WB2_Sheet.cell_value(x,0) != WB1_Sheet.cell_value(y,0):
            break
first_match_offset=0
for x in range(m,Last_row):
    for counter in range(0,30):
            #checking matching test cases in next 20 test cases 
            #they are sorted such that the test case may appear in next 50 lines or they are not present
            y=x+counter
            if x>Last_row or y>Last_row:
                y=y-counter
                break;
    if WB2_Sheet.cell_value(x,0) == WB1_Sheet.cell_value(y,0):
        first_match_offset = y-m
print first_match_offset
wb_output.save("result.xls')
#its incomplete... need help to complete this thing

1 个答案:

答案 0 :(得分:0)

我认为如果使用set()数据类型会更好。只需为每个工作簿中的观察创建一个集合,然后比较这些集合,如:

#create empty set
setA = set()
#then you loop all registers and add them to your set
setA.add(WB1_Sheet.cell_value(y,0))

#later create a setB for WB2

#to get a list of the matching records in both sets:
matchList = setA & setB

#If you want to know the items of A that are not in B:
missing = setA - setB

#If you want to know all the discrepancies
discrepancies = setA ^ setB