由于工作中经常需要对Excel第一列数据进行超链接处理,之前都是手动处理,借助AI cursor 的力量,可以自动化实现进行统一处理
上代码
python
import openpyxl
from openpyxl.styles import Font
def add_hyperlinks_to_first_column(input_file, output_file=None):
"""
读取Excel第一列的数字,添加超链接,并保持显示为数字。
:param input_file: 输入Excel文件路径
:param output_file: 输出Excel文件路径,默认为覆盖原文件
"""
if not output_file:
output_file = input_file
try:
wb = openpyxl.load_workbook(input_file)
except FileNotFoundError:
print(f"错误: 找不到文件 {input_file}")
return
except Exception as e:
print(f"错误: 无法打开文件 {e}")
return
ws = wb.active
base_url = "http://贴你自己的网址?id="
max_row = ws.max_row
print(f"正在处理: {max_row} 行数据...")
count = 0
for row in range(1, max_row + 1):
cell = ws.cell(row=row, column=1)
val = cell.value
# 检查是否为有效数字ID
if val is not None:
try:
# 统一转换为整数以构建URL
if isinstance(val, float) and val.is_integer():
id_num = int(val)
elif isinstance(val, int):
id_num = val
elif isinstance(val, str) and val.strip().isdigit():
id_num = int(val.strip())
else:
continue
full_url = f"{base_url}{id_num}"
# 关键步骤:
# 1. 设置单元格的 hyperlink 属性为完整URL
# 2. 保持 cell.value 不变(即保持显示为数字)
cell.hyperlink = full_url
# 可选:设置字体样式以提示用户这是可点击的链接(蓝色+下划线)
# 注意:这不会改变单元格的值,只改变外观
cell.font = Font(color="0563C1", underline="single")
count += 1
except ValueError:
continue
try:
wb.save(output_file)
print(f"完成!已为 {count} 个单元格添加超链接。")
print(f"保存至: {output_file}")
except Exception as e:
print(f"保存失败: {e}")
if __name__ == "__main__":
# 请替换为你的实际文件名
filename = "data.xlsx"
add_hyperlinks_to_first_column(filename)
最终实践可以执行
C:\Users\liuw\PycharmProjects\pythonProject\venv\Scripts\python.exe C:\Users\liuw\PycharmProjects\pythonProject\add_hyperlinks.py
正在处理: 95 行数据...
完成!已为 94 个单元格添加超链接。
保存至: data.xlsx
Process finished with exit code 0