I'm using the module openpyxl for Python and am trying to create a hyperlink that will take me to a different tab in the same Excel workbook. Doing something similar to the following creates the hyperlink; however, when I click on it, it tells me it can't open the file.
from openpyxl import Workbook
wb = Workbook()
first_sheet = wb.create_sheet(title='first')
second_sheet = wb.create_sheet(title='second')
first_sheet['A1'] = "hello"
second_sheet['B2'] = "goodbye"
link_from = first_sheet['A1']
link_to = second_sheet['B2'].value
link_from.hyperlink = link_to
wb.save("C:/somepath/workbook.xlsx")
I'm assuming the issue lies in the value of 'link_to'; however, I don't know what would need changed or what kind of path I would have to write.
I'm using Python 2.7.6 and Excel 2013.
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")
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':
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'
.In addition to the previous answers, it is also useful to format the cell to make it look like the hyperlinks created within Excel. To do this use the Excel style named "Hyperlink", as per example below which also includes using single quotes around sheet names in case they include spaces (as mentioned by Neofish).
Support for hyperlinks in openpyxl is currently extremely rudimentary and largely limited to reading the links in existing files.
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.