python实现两个excel数据匹配,最终写入新的excel文件

需求背景

表1有两列

表2包含表1不过缺少坐标字段

需要根据HID匹配两个表,把表1的坐标内容补充到表2

代码

import shutil
import sys
import xlwt
import xlrd

file1 = "C:\\Users\\xuyin\\Desktop\\新建文件夹\\match-excel\\表1.xls"
#打开表1
wb1 = xlrd.open_workbook(filename=file1)
# 表1要匹配的列索引
hid_index1 = 0
# 表1目标数据列索引
target_index1 = 1
# 表1的sheet
sheet1 = wb1.sheet_by_index(0)
# 表1的sheet的总行数
rowNum1 = sheet1.nrows
# 表1的sheet的总列数
colNum1 = sheet1.ncols

file2 = "C:\\Users\\xuyin\\Desktop\\新建文件夹\\match-excel\\表2.xls"
#打开表2
wb2 = xlrd.open_workbook(filename=file2)#打开文件
# 表2要匹配的列索引
hid_index2 = 0
# 表2目标数据列索引
target_index2 = 2
# 表2的sheet
sheet2 = wb2.sheet_by_index(0)#通过索引获取表格
# 表2的sheet的总行数
rowNum2 = sheet2.nrows
# 表2的sheet的总列数
colNum2 = sheet2.ncols

# xlwt准备生成一个新的文件
write_workbook = xlwt.Workbook()
write_sheet = write_workbook.add_sheet('sheet1',cell_overwrite_ok=True)

for index2 in range(0,rowNum2):
	for col_index in range(0,colNum2):
		# 遍历表2的每一行每一列,把对应的单元设置到新的文件中,即复制了表2的数据
		write_sheet.write(index2,col_index,sheet2.cell_value(index2,col_index))
		# 在遍历列过程中,如果碰到目标数据列索引.即需要补充的字段,则进行遍历表1,判断的id索引匹配
		if col_index == target_index2:
			for index1 in range(1,rowNum1):
				hid1 = sheet1.cell_value(index1,hid_index1)
				if hid1 == sheet2.cell_value(index2,hid_index2):
					# 如果两个表的id相同则把表1的单元内容设置到表2对应的单元格
					write_sheet.write(index2,col_index,sheet1.cell_value(index1,target_index1))

# 保存新的文件
write_workbook.save('new.xls')

结果

原有文件新增sheet

比如在表2新增一个sheet保存结果,在上面的代码上做修改

sheet2 = wb2.sheet_by_index(0)#通过索引获取表格
# 表2的sheet的总行数
rowNum2 = sheet2.nrows
# 表2的sheet的总列数
colNum2 = sheet2.ncols
 
# xlwt准备生成一个新的文件
# write_workbook = xlwt.Workbook()
# write_sheet = write_workbook.add_sheet('sheet1',cell_overwrite_ok=True)

from xlutils.copy import copy
write_workbook = copy(wb2)
write_sheet = write_workbook.add_sheet('新建的sheet',cell_overwrite_ok=True)
 
for index2 in range(0,rowNum2):
	for col_index in range(0,colNum2):
		# 遍历表2的每一行每一列,把对应的单元设置到新的文件中,即复制了表2的数据
		write_sheet.write(index2,col_index,sheet2.cell_value(index2,col_index))
		# 在遍历列过程中,如果碰到目标数据列索引.即需要补充的字段,则进行遍历表1,判断的id索引匹配
		if col_index == target_index2:
			for index1 in range(1,rowNum1):
				hid1 = sheet1.cell_value(index1,hid_index1)
				if hid1 == sheet2.cell_value(index2,hid_index2):
					# 如果两个表的id相同则把表1的单元内容设置到表2对应的单元格
					write_sheet.write(index2,col_index,sheet1.cell_value(index1,target_index1))
 
# 保存新的文件
write_workbook.save(file2)

  • 28
    点赞
  • 207
    收藏
    觉得还不错? 一键收藏
  • 30
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 30
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值