How to create a hyperlink to a different Excel sheet in the same workbook

旧街凉风 提交于 2019-12-05 05:00:32

Support for hyperlinks in openpyxl is currently extremely rudimentary and largely limited to reading the links in existing files.

lomelisan

I found a way to do it.

Assuming one .xlsx file named 'workbookEx.xlsx' with two sheets named 'sheet1' and 'sheet2' and needing a link from one cell(A1) of the 'sheet1' to another cell(E5) of the 'sheet2':

from openpyxl import load_workbook

wb = load_workbook(workbookEx.xlsx) 
ws = wb.get_sheet_by_name("sheet1")

link = "workbookEx.xlsx#sheet2!E5"

ws.cell(row=1, column=1).hyperlink = (link)

The secret was the "#", Excel do not shows you but it uses the '#' for same file links, I just had to copy a same file link created in Excel to a Word document to see the '#'.

It is also possible to omit the filename, i.e. to link against a sheet of the active document just use: _cell.hyperlink = '#sheetName!A1'.

To name the link you just created, just set the cell value to the desired string: _cell.value = 'Linkname'.

Another working solution is to use excels built in function HYPERLINK. It doesn't make the value in the cell into a hyperlink but put a formula in the cell and act like a hyperlink.

ws.cell('A1').value = '=HYPERLINK("#sheet2!E5","Link name")'

As an addendum to Marcus.Luck's answer, if wanting to use Excel's built-in hyperlink function directly, you may need to format as:

'=HYPERLINK("{}", "{}")'.format(link, "Link Name")

Without this formatting, the file didn't open for me without needing repair, which removed the cell values when clicking the links.

e.g. ws.cell(row=1, column=1).value = '=HYPERLINK("{}", "{}")'.format(link, "Link Name")

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!