需求是有两个Excel文件:1.xlsx,2.xlsx,比较2.xlsx中的A,B列和1.xlsx中的A,B列;查找1.xlsx中存在,2.xlsx中不存在的行数据,输出到result.xlsx文件中
1.xlsx内容如下
2.xlsx内容如下
上代码
# coding=utf-8
import xlrd
import xlwt
# 打开文件
#data = xlrd.open_workbook(\'./附件7:溶洞钻孔、埋管、注浆.xlsx\')
# 查看工作表
#data.sheet_names()
#print("sheets:" + str(data.sheet_names()))
# 通过文件名获得工作表,获取工作表1
#table = data.sheet_by_name(\'20200404\')
# 打印data.sheet_names()可发现,返回的值为一个列表,通过对列表索引操作获得工作表1
# table = data.sheet_by_index(0)
# 获取行数和列数
# 行数:table.nrows
# 列数:table.ncols
#print("总行数:" + str(table.nrows))
#print("总列数:" + str(table.ncols))
# 获取整行的值 和整列的值,返回的结果为数组
# 整行值:table.row_values(start,end)
# 整列值:table.col_values(start,end)
# 参数 start 为从第几个开始打印,
# end为打印到那个位置结束,默认为none
#print("整行值:" + str(table.row_values(0)))
#print("整列值:" + str(table.col_values(1)))
# 合并第0行的第0列到第3列。
worksheet.write_merge(0, 0, 0, 3, \'First Merge\')
worksheet.write_merge(1, 2, 0, 3, \'Second Merge\', style)
worksheet.write_merge(4, 6, 3, 6, \'My merge\', style)
#worksheet.write_merge(开始行,结束行, 开始列, 结束列, \'My merge\', style)
如果设置颜色,样式,参考: https://www.cnblogs.com/machangwei-8/p/10738244.html
#pattern = xlwt.Pattern() # 创建模式对象Create the Pattern
#pattern.pattern = xlwt.Pattern.SOLID_PATTERN # May be: NO_PATTERN, SOLID_PATTERN, or 0x00 through 0x12
#pattern.pattern_fore_colour = 5 #设置模式颜色 May be: 8 through 63. 0 = Black, 1 = White, 2 = Red, 3 = Green, 4 = Blue, 5 = Yellow, 6 = Magenta, 7 = Cyan, 16 = Maroon, #17 = Dark Green, 18 = Dark Blue, 19 = Dark Yellow , almost brown), 20 = Dark Magenta, 21 = Teal, 22 = Light Gray, 23 = Dark Gray, the list goes on...
#style = xlwt.XFStyle() # 创建样式对象Create the Pattern
#style.pattern = pattern # 将模式加入到样式对象Add Pattern to Style
# 获取某个单元格的值,例如获取B3单元格值
#cel_B3 = table.cell(3,2).value
#print("第三行第二列的值:" + cel_B3)
def read_xlrd(excelFile,tablename):
data = xlrd.open_workbook(excelFile)
#table = data.sheet_by_index(0)
table = data.sheet_by_name(tablename)
print("总行数:" + str(table.nrows))
print("总列数:" + str(table.ncols))
dataFile = []
for rowNum in range(table.nrows):
# if 去掉表头
if rowNum > 0:
dataFile.append(table.row_values(rowNum))
return dataFile
workbook = xlwt.Workbook(encoding = \'ascii\')
worksheet = workbook.add_sheet(\'sheet1\')
def writeLine(row ,line):
col=0
while col <len(line):
worksheet.write(row,col, line[col])
col+=1
filename1=\'./附件7:溶洞钻孔、埋管、注浆.xlsx\'
data1=read_xlrd(filename1,\'20200404\')
filename2=\'./设计之都溶洞注浆台账.xlsx\'
data2=read_xlrd(filename2,\'Sheet1\')
data=[]
for row in data1[4:]:
#print(row[0],row[1])
data.append([row[0],row[1]])
#print(data)
result=[]
i=0
for row in data2[1:]:
buf=[row[1],row[2]]
if buf not in data:
print(row,\'不存在\')
writeLine(i, row)
i+=1
workbook.save(\'result.xlsx\')
之后生成结果result.xlsx文件