Borrowing heavily from this question, as I couldn't find anything on SO to link to as a duplicate...
This code will create a Hyperlink in cells A1:A9
import win32com.client
excel = r'I:\Custom_Scripts\Personal\Hyperlinks\HyperlinkTest.xlsx'
xlApp = win32com.client.Dispatch("Excel.Application")
workbook = xlApp.Workbooks.Open(excel)
worksheet = workbook.Worksheets("Sheet1")
for xlRow in xrange(1, 10, 1):
worksheet.Hyperlinks.Add(Anchor = worksheet.Range('A{}'.format(xlRow)),
Address="http://www.microsoft.com",
ScreenTip="Microsoft Web Site",
TextToDisplay="Microsoft")
workbook.Save()
workbook.Close()
And here is a link to the Microsoft Documentation for the Hyperlinks.Add() method.
python - adding hyperlinks in some cells openpyxl - Stack Overflow
python - Create a hyperlink to a different Excel sheet in the same workbook - Stack Overflow
python - add hyperlink to excel sheet created by pandas dataframe to_excel method - Stack Overflow
Insert hyperlink to a local folder in Excel with Python - Stack Overflow
This works for me:
wbook.active['A8'].hyperlink = "http://www.espn.com"
wbook.active['A8'].value = 'ESPN'
wbook.active['A8'].style = "Hyperlink"
If wanting to use Excel's built in hyperlink function directly, you can use the following to format as a link:
'=HYPERLINK("{}", "{}")'.format(link, "Link Name")
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':
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'.
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")
Building on the approach by @guillaume-jacquenot we can use apply to apply this to an entire Series.
df = pd.DataFrame({'Year': [2000, 2001, 2002 , 2003]})
For cleanliness, I wrote a helper method.
def make_hyperlink(value):
url = "https://custom.url/{}"
return '=HYPERLINK("%s", "%s")' % (url.format(value), value)
Then, apply it to the Series:
df['hyperlink'] = df['Year'].apply(make_hyperlink)
Year hyperlink
0 2000 =HYPERLINK("https://custom.url/2000", "2000")
1 2001 =HYPERLINK("https://custom.url/2001", "2001")
2 2002 =HYPERLINK("https://custom.url/2002", "2002")
3 2003 =HYPERLINK("https://custom.url/2003", "2003")
You could use the HYPERLINK function
import pandas as pd
df = pd.DataFrame({'link':['=HYPERLINK("http://www.someurl.com", "some website")']})
df.to_excel('test.xlsx')
The XlsxWriter write_url() method allows you to link to folders or other workbooks and worksheets as well as internal links and links to web urls. For example:
import xlsxwriter
workbook = xlsxwriter.Workbook('links.xlsx')
worksheet = workbook.add_worksheet()
worksheet.set_column('A:A', 50)
# Link to a Folder.
worksheet.write_url('A1', r'external:C:\Temp')
# Link to a workbook.
worksheet.write_url('A3', r'external:C:\Temp\Book.xlsx')
# Link to a cell in a worksheet.
worksheet.write_url('A5', r'external:C:\Temp\Book.xlsx#Sheet1!C5')
workbook.close()
See the docs linked to above for more details.
Here is the code that did the trick:-
# Creates hyperlink in existing workbook...
def set_hyperlink():
from openpyxl import load_workbook
x = "hyperlink address"
wb = load_workbook("filename.xlsx")
ws = wb.get_sheet_by_name("sheet_name")
ws.cell(row = x?, column = y?).hyperlink = x
wb.save("filename.xlsx")
set_hyperlink()
Tried again with openpyxl as advised.
Hello,
I have an excel file with hyperlinks (these hyperlinks lead to a website). I want to python to open one of the hyperlinks. When I execute the script I would expect the websites to open in Microsoft edge, but instead, nothing happens. Here is my code:
import openpyxl
wb = openpyxl.load_workbook("C:\\Users\\rfog\\OneDrive\\Documents\\Python Excel\\pythontest.xlsx")
ws = wb['Sheet1']
ws.cell(row=1, column=2).hyperlink.target
Any suggestions?
I am using python to generate a daily report, which is published as an Excel 2016 file. One column of the report will have links to .pdf files on a network share.
Attempts to hardcode the network path/file name (e.g., "T:\District\Parks\GIS\PDFs") generate a "Cannot open the specified file" error message. I have checked and the path and filenames are correct.
According to Bill Manville's answer on https://answers.microsoft.com/en-us/msoffice/forum/msoffice_excel-mso_other-mso_archive/excel-hyperlink-cannot-open-specified-file/77c6ef20-f472-453e-a88d-71e9a7a23138 , "Hyperlinks are sometimes stored as relative to the folder that contains the workbook. " This seems to be the case here. When I followed Mr. Manville's suggestion of "setting File > Properties > Summary > Hyperlink base to\\NoServer\Nofolder or some other non-existent location.", without changing anything in the hyperlinks, the hyperlinks work.
How do I access the Hyperlink Base property programmatically? Can it be done programmatically? I'll do it manually every day if necessary, but it would obviously be more consistent/faster to do it through code.
I have gone through the openpyxl documentation and have not seen anything helpful. Google/DDG searches are equally fruitless.
Thanks.
Try this:
def CreateLink():
excel.Worksheets(1).Cells(1,1).Value = '=HYPERLINK(A21,"Cell A21")'
Use xlsxwriter module to do it as simple as it is, have a look at the documentation
# Link to a cell on the current worksheet.
worksheet.write_url('A1', 'internal:Sheet2!A1')
# Link to a cell on another worksheet.
worksheet.write_url('A2', 'internal:Sheet2!A1:B2')
# Worksheet names with spaces should be single quoted like in Excel.
worksheet.write_url('A3', "internal:'Sales Data'!A1")
# Link to another Excel workbook.
worksheet.write_url('A4', r'external:c:\temp\foo.xlsx')
# Link to a worksheet cell in another workbook.
worksheet.write_url('A5', r'external:c:\foo.xlsx#Sheet2!A1')
# Link to a worksheet in another workbook with a relative link.
worksheet.write_url('A7', r'external:..\foo.xlsx#Sheet2!A1')
# Link to a worksheet in another workbook with a network link.
worksheet.write_url('A8', r'external:\\NET\share\foo.xlsx')