由于一些原因,需要对比两张excel表格中数据的差异,但是两张表中的数据又太多,实在是难以下手。于是想到了pytho中的xlrd(读取表格)、xlwt(写入表格)库,或许可以帮助我轻松地完成这项工作,于是花了一点时间写了一个数据对比的程序。
接下来是实现方法:
导入xlrd、xlwt库
import xlrd import xlwt from xlutils.copy import copy # 创建数据对比的类 class CheckValue: # 初始化 def __init__(self, table_, table_new, wd_, ws_): self.table_ = table_ # 初始化原数据表对象 self.table_new = table_new # 初始化对比数据表对象 self.wd = wd_ # 初始化拷贝数据表 self.ws = ws_ # 数据对比的类方法 def check_value(self): num = [] # 创建一个列表用于储存num字段, 用于储存正确信息 name = [] # 创建一个列表用于储存name字段 class_ = [] # 创建一个列表用于储存class字段
# 创建表格样式, 如果对比的信息正确, 则将表格的背景色渲染为绿色
style = xlwt.XFStyle()
pattern = xlwt.Pattern()
pattern.pattern = xlwt.Pattern.SOLID_PATTERN
pattern.pattern_fore_colour = 3
style.pattern = pattern
print("开始检索数据...")
# 使用for循环检索表格数据
# 先查找出对比数据表的一行数据,然后检索原数据表的每一行数据,并与前者的数据进行对比,如果都正确,则输出新表
for i in range(2, int(self.table_new.nrows)): for j in range(1, int(self.table.nrows)): if self.table_new.cell_value(i, 1) == self.table.cell_value(j, 0): num.append(self.table_new.cell_value(i, 1))
self.ws.write(i, 1, self.table_new.cell_value(i, 1), style=style)
if self.table_new.cell_value(i, 2) == self.table.cell_value(j, 1):
name.append(self.table_new.cell_value(i, 2))
self.ws.write(i, 2, self.table_new.cell_value(i, 2), style=style)
if self.table_new.cell_value(i, 3) == self.table.cell_value(j, 4):
class_.append(self.table_new.cell_value(i, 3))
self.ws.write(i, 3, self.table_new.cell_value(i, 3), style=style)
self.wd.save(r"C:\CS\XXXX.xls") # 输出对比后的表
else:
continue # 如果数据不正确,则不进行渲染,跳入下一个循环
else:
continue
else:
continue
print("数据检索完毕,num共有{0}条数据正确, name共有{1}条数据正确, class_共有{2}条数据正确".format(len(num), len(name), len(class_)))
print("运行结束!")
ori_data = xlrd.open_workbook(r"C:\CS\X1.slxs")# 打开原数据表格
table = ori_data.sheets()[0]
new_data = xlrd.open_workbook(r"C:\CS\X2.slx")# 打开需要对比数据的表格
table_new = new_data.sheets()[0]
wb = copy(new_data) # 创建数据表拷贝
ws = wb.get_sheet(0)
v = CheckValue(table, table_new, wd, ws) # 创建一个CheckValue对象
v.check_value() # 使用对象的check_value()方法
运行之后,只需要等待20秒左右,即可对比完成。
上述代码只使用了for循环与if判断语句,当然还有更高效的方法,即使用多线程,以后有时间再来进行改进。