使用场景:
若干Sheet页,前一个Sheet第二列每一个单元格,如果与后一个Sheet中第一列的一个单元格内容相等,为前一个Sheet中的第二列的单元格添加超链接到后一个Sheet页中的对应单元格
import openpyxl
from openpyxl.worksheet.hyperlink import Hyperlink
# 打开Excel文件
workbook = openpyxl.load_workbook('E:/SP3D-DOC/TestExportSchema-2.xlsx')
# 遍历每个工作表(从第一个到倒数第二个)
for sheet_index in range(len(workbook.sheetnames) - 1):
current_sheet = workbook.worksheets[sheet_index]
next_sheet = workbook.worksheets[sheet_index + 1]
# 遍历第一个工作表的第二列数据
for row in current_sheet.iter_rows(min_row=1, min_col=2, max_row=current_sheet.max_row, max_col=2):
for cell in row:
cell_value = cell.value
# 在下一个工作表中查找匹配的内容
for next_row in next_sheet.iter_rows(min_row=1, min_col=1, max_row=next_sheet.max_row, max_col=1):
for next_cell in next_row:
# print('cell_value:', cell_value)
# print('nex_cell.value', next_cell.value)
if cell_value == next_cell.value:
# 创建超链接
print('next_cell.coordinate:', next_cell.coordinate)
# link_address = f"E:/SP3D-DOC/test-macro.xlsx-{next_sheet.title}!{next_cell.coordinate}-"
link_add = f"{next_sheet.title}!{next_cell.coordinate}"
# print('Link address:', link_address)
cell.hyperlink = Hyperlink(ref=cell.coordinate, location=link_add) # reference=
cell.style = 'Hyperlink'
# 保存修改后的Excel文件
workbook.save('E:/SP3D-DOC/TestExportSchema-2.xlsx')