简体   繁体   中英

How do I use variable names in hyperlinks?

I have tried using the following Python code to create hyperlinks using openpyxl in Python. 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. Finding code examples for openpyxl has been challenging also. 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 :

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.

EDIT: replaced wb.get_sheet_by_name('Sheet1') with ws1 = wb['Sheet1'] because DeprecationWarning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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