简体   繁体   English

如何在超链接中使用变量名?

[英]How do I use variable names in hyperlinks?

I have tried using the following Python code to create hyperlinks using openpyxl in Python.我尝试使用以下 Python 代码在 Python 中使用 openpyxl 创建超链接。 I tried using variable names but got the error "Reference isn't valid".我尝试使用变量名,但收到错误“引用无效”。 I also tried using Excel Sheet names with spaces in them which is valid in Excel but the openpyxl hyper link command does not seem to work with them.我还尝试使用 Excel 表格名称,其中包含空格,这在 Excel 中有效,但 openpyxl 超链接命令似乎不适用于它们。 Finding code examples for openpyxl has been challenging also.为 openpyxl 查找代码示例也具有挑战性。 Here is the code:这是代码:

from openpyxl import load_workbook

xlsFile = 'e:\\exceltest1.xlsx'
wbook = load_workbook(xlsFile)
Sheet7Name = "Sheet7"
worksheet7 = wbook.create_sheet(title=Sheet7Name)
worksheet9 = wbook.create_sheet(title="Sheet9")
worksheet10 = wbook.create_sheet(title="Sheet 10")
worksheet7.cell(row=3, column=4, value="Go to A1 s9 from D3 s7").hyperlink = '#Sheet9!A1'
worksheet7.cell(row=1, column=1, value="Go to D3 s9 from A1 s7").hyperlink = '#Sheet9!D3'
worksheet7.cell(row=2, column=1, value="Go to A3 s9 from A2 s7").hyperlink = '#Sheet9!A3'
worksheet7.cell(row=4, column=5, value="Go to E6 s7  from E4 s7").hyperlink = '#Sheet7Name!E6'
worksheet7.cell(row=6, column=5, value="Go to E4 s7 from E6 s7").hyperlink = '#Sheet7Name!E4'
worksheet9.cell(row=4, column=1, value="Go to A7 s7 from A4 s9").hyperlink = '#Sheet7Name!A7'
worksheet9.cell(row=3, column=4, value="Go to A1 s9 from D3 s9").hyperlink = '#Sheet9!A1'
worksheet9.cell(row=1, column=1, value="Go to D3 s9 from A1 s9").hyperlink = '#Sheet9!D3'
worksheet9.cell(row=2, column=1, value="Go to A3 s9 from A2 s9").hyperlink = '#Sheet9!A3'
worksheet10.cell(row=2, column=1, value="Go to A3 s10 from A2 s10").hyperlink = '#Sheet 10!A3'
wbook.save(xlsFile)

You can try this - to link cell 1 in Sheet1 to A1 cell in Sheet9 :您可以试试这个 - 将Sheet1中的cell 1链接到Sheet9中的A1 cell

file_name = "your-excel-file.xlsx"
wb = load_workbook(file_name) 
ws1 = wb['Sheet1']

# Create hyperlink to relevant cell
link = file_name+"#Sheet9!A1"

ws1.cell(row=1, column=1).hyperlink = link
ws1.cell(row=1, column=1).value = "Refer to Sheet 9 - Cell A1"
ws1.cell(row=1, column=1).style = "Hyperlink"

wb.save(file_name)

And do it for the rest cells you want to hyperlink.并为您想要超链接的 rest 单元格执行此操作。

EDIT: replaced wb.get_sheet_by_name('Sheet1') with ws1 = wb['Sheet1'] because DeprecationWarning.编辑:wb.get_sheet_by_name('Sheet1')替换为ws1 = wb['Sheet1']因为 DeprecationWarning。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM