有两个表格11.xlsx、22.xlsx,其中两个表格可以通过‘就医登记号’进行联合,现在需要通过核对两者的金额,如果不相等则抽出来把22.xlsx的数据标红色并存储到新的表格中。以下是test表格:
表格11.xlsx
表格22.xlsx
为了实现以上功能,编写以下代码:
import openpyxl
from openpyxl.styles import Font
def compare_and_mark(file1, files_to_compare, output_file, cost_columns_file1, cost_columns_files_to_compare):
# 加载第一个工作簿
wb1 = openpyxl.load_workbook(file1)
sheet1 = wb1.active
# 字体设置为红色
red_font = Font(color="FF0000")
# 用于存储不匹配的就医登记号及对应的文件名
unmatched_reg_numbers = {file1: []}
# 对每个文件进行比对
for idx, file_to_compare in enumerate(files_to_compare):
# 加载文件
wb_compare = openpyxl.load_workbook(file_to_compare)
sheet_compare = wb_compare.active
# 获取当前比对文件的费用字段名列表
cost_columns_compare = cost_columns_files_to_compare[idx]
# 对第一个文件的每一行进行遍历
for row1 in sheet1.iter_rows(min_row=2, values_only=True):
#根据实际情况修改
reg_no1 = row1[0] # 第一列是就医登记号
found = False
# 在比对文件中查找相同的就医登记号
for row2 in sheet_compare.iter_rows(min_row=2, values_only=True):
#根据实际情况修改
reg_no2 = row2[0] # 第一列是就医登记号
if reg_no1 == reg_no2:
found = True
# 比较费用,如果不相同则记录就医登记号和文件名
for i in range(1, len(row1)): # 从第二列开始比较费用
cost1 = row1[i]
cost2 = row2[cost_columns_compare[i - 1]] # 根据当前文件的费用字段名索引获取对应费用值
if cost1 != cost2:
if file_to_compare not in unmatched_reg_numbers:
unmatched_reg_numbers[file_to_compare] = []
unmatched_reg_numbers[file_to_compare].append(str(reg_no1)) # 转换为字符串类型
break
break
# 如果找不到就医登记号,则将整行标红
if not found:
if file_to_compare not in unmatched_reg_numbers:
unmatched_reg_numbers[file_to_compare] = []
unmatched_reg_numbers[file_to_compare].append(str(reg_no1)) # 转换为字符串类型
# 在需要对比的表格中标红不匹配的就医登记号
for file, reg_numbers in unmatched_reg_numbers.items():
wb_compare = openpyxl.load_workbook(file)
sheet_compare = wb_compare.active
# 对比文件中不再使用values_only=True参数
for row in sheet_compare.iter_rows(min_row=2, max_row=sheet_compare.max_row, min_col=1, max_col=1):
for cell in row:
if str(cell.value) in reg_numbers: # 转换为字符串类型进行比较
for col_idx, cell_in_row in enumerate(row):
cell_in_row.font = red_font
break
# 保存修改后的文件
wb_compare.save(file)
# 使用示例
files_to_compare = ['22.xlsx'] # 要比对的文件列表
cost_columns_files_to_compare = [[1, 2, 3]] # 每个文件对应的费用字段名索引列表
compare_and_mark('11.xlsx', files_to_compare, 'output.xlsx', ['费用1', '费用2', '费用3'], cost_columns_files_to_compare)
结果out.xlsx表格