最近工作中经常需要做数据对比,用excel公式也很方便,但刚好正在学习Python,所以就想用Python来实现数据对比
操作步骤如下:
-
安装xlrd库
cd进入Python安装目录,执行pip install xlrd -
准备数据
import xlrd
#导入xlrd模块
data = xlrd.open_workbook(r'C:\Users\admin\xxx\xx.xlsx')
#打开excel文件
data.sheet_names()
print('sheet:'+str(data.sheet_names()))
#查看py_tst.xlsx文件中的工作表
table1 = data.sheet_by_index(0)
table2 = data.sheet_by_index(1)
# 打印data.sheet_names()可发现,返回的值为一个列表,通过对列表索引操作获得工作表1,工作表2
col1 = table1.col_values(0)
col2 = table2.col_values(0)
diff = []
for i in col1:
if i not in col2:
diff.append(i)
print(diff)
data = open(r"C:\Users\admin\Desktop\diff.xlsx",'w',encoding='utf-8')
data.write("different\n")
for m in range(len(diff)):
data.write(str(diff[m]))
data.write('\n')
data.close()
运行结果:
但写入数据的excel确无法打开了,只能用sublime Text以文本形式打开,小编也是个小白,正在找原因中~~,知道原因和解决方案的小伙伴们可以给我留言哦