使用openpyxl模块比对两个excel表格

 

 

需求:

集团发了一张即将下线的服务器台账表格,里面有整个集团个部门计划下线的服务器列表,大概有三五百行,但是我们部门只有80多台服务器,还不一定都包含在集团下发的表格里。手动一个个去查比较麻烦,写了个python脚本去检测两个表格中相同的地方,并返回单元格信息。

第一步、取出我们台账的所有ip存到列表里

from openpyxl import load_workbook

base_path=r"C:\Users\31317\Desktop\tmp\表格\云主机资源列表.xlsx"
# 获取第一个sheet对象
b_sheet = load_workbook(base_path).worksheets[0]

target_list = []

def get_target(sheet, foo_list):
    column=sheet['H']          # 第H列是IP地址
    for cell in column:
        if cell.value:
            foo_list.append(cell.value)
    return foo_list


target_list = get_target(b_sheet, target_list)

第二步、先从集团表中找一个值

from openpyxl import load_workbook

compare_path=r"C:\Users\31317\Desktop\tmp\表格\集团云服务器下线清单.xlsx"

# 集团的表格,服务器信息在第二个sheet中,所以下标是1
c_sheet = load_workbook(compare_path).worksheets[1]

# 定义函数find_cell,传递sheet对象和查询值
def find_cell(sheet, target_value):
    for row in sheet.iter_rows():
        for cell in row:
            if target_value.lower() in str(cell.value).lower():
                return cell.coordinate  # 返回匹配的单元格位置
    return None

# 调用函数查找单元格位置
cell_position = find_cell(sheet, target_value)

if cell_position:
    print(f"A cell containing '{target_value}' is located at: {cell_position}")
else:
    print(f"No cell containing '{target_value}' found in the sheet.")

 

第三步、我们循环的去集团表里去找

from openpyxl import load_workbook

base_path=r"C:\Users\31317\Desktop\tmp\表格\IT云主机资源及项目列表.xlsx"

compare_path=r"C:\Users\31317\Desktop\tmp\表格\IT云信息化域资源申请清单.xlsx"


b_sheet = load_workbook(base_path).worksheets[0]
c_sheet = load_workbook(compare_path).worksheets[1]

target_list = []
position_list = []


def get_target(sheet, foo_list):
    column=sheet['H']
    for cell in column:
        if cell.value:
            foo_list.append(cell.value)
    return foo_list


target_list = get_target(b_sheet, target_list)


def find_cell(sheet, target_value):
    for row in sheet.iter_rows():
        for cell in row:
            if target_value.lower() in str(cell.value).lower():
                return cell.coordinate  # 返回匹配的单元格位置
    return None


for i in target_list:
    cell_position = find_cell(c_sheet, i)
    if cell_position:
        print(cell_position)
        position_list.append(cell_position)
print(position_list)

上面说了,我们的服务器只有80台,所以拿我们的ip去集团表里查,这样查询的次数少一些。

 

posted @ 2024-03-14 14:16  高佳丰  阅读(92)  评论(0编辑  收藏  举报