This can be done with openpyxl, I'm not sure its possible with Pandas at all. Here's how I've done it:
import openpyxl
wb = openpyxl.load_workbook('yourfile.xlsm')
sheets = wb.sheetnames
ws = wb[sheets[0]]
# Deprecation warning
# ws = wb.get_sheet_by_name('Sheet1')
print(ws.cell(row=2, column=1).hyperlink.target)
You can also use iPython, and set a variable equal to the hyperlink object:
t = ws.cell(row=2, column=1).hyperlink
then do t. and press tab to see all the options for what you can do with or access from the object.
This can be done with openpyxl, I'm not sure its possible with Pandas at all. Here's how I've done it:
import openpyxl
wb = openpyxl.load_workbook('yourfile.xlsm')
sheets = wb.sheetnames
ws = wb[sheets[0]]
# Deprecation warning
# ws = wb.get_sheet_by_name('Sheet1')
print(ws.cell(row=2, column=1).hyperlink.target)
You can also use iPython, and set a variable equal to the hyperlink object:
t = ws.cell(row=2, column=1).hyperlink
then do t. and press tab to see all the options for what you can do with or access from the object.
Quick monkey patching, without converters or anything like this, if you would like to treat ALL cells with hyperlinks as hyperlinks, more sophisticated way, I suppose, at least be able to choose, what columns treat as hyperlinked or gather data, or save somehow both data and hyperlink in same cell at dataframe. And using converters, dunno. (BTW I played also with data_only, keep_links, did not helped, only changing read_only resulted ok, I suppose it can slow down your code speed).
P.S.: Works only with xlsx, i.e., engine is openpyxl
P.P.S.: If you reading this comment in the future and issue https://github.com/pandas-dev/pandas/issues/13439 still Open, don't forget to see changes in _convert_cell and load_workbook at pandas.io.excel._openpyxl and update them accordingly.
import pandas
from pandas.io.excel._openpyxl import OpenpyxlReader
import numpy as np
from pandas._typing import FilePathOrBuffer, Scalar
def _convert_cell(self, cell, convert_float: bool) -> Scalar:
from openpyxl.cell.cell import TYPE_BOOL, TYPE_ERROR, TYPE_NUMERIC
# here we adding this hyperlink support:
if cell.hyperlink and cell.hyperlink.target:
return cell.hyperlink.target
# just for example, you able to return both value and hyperlink,
# comment return above and uncomment return below
# btw this may hurt you on parsing values, if symbols "|||" in value or hyperlink.
# return f'{cell.value}|||{cell.hyperlink.target}'
# here starts original code, except for "if" became "elif"
elif cell.is_date:
return cell.value
elif cell.data_type == TYPE_ERROR:
return np.nan
elif cell.data_type == TYPE_BOOL:
return bool(cell.value)
elif cell.value is None:
return "" # compat with xlrd
elif cell.data_type == TYPE_NUMERIC:
# GH5394
if convert_float:
val = int(cell.value)
if val == cell.value:
return val
else:
return float(cell.value)
return cell.value
def load_workbook(self, filepath_or_buffer: FilePathOrBuffer):
from openpyxl import load_workbook
# had to change read_only to False:
return load_workbook(
filepath_or_buffer, read_only=False, data_only=True, keep_links=False
)
OpenpyxlReader._convert_cell = _convert_cell
OpenpyxlReader.load_workbook = load_workbook
And after adding this above in your python file, you will be able to call df = pandas.read_excel(input_file)
After writing all this stuff it came to me, that maybe it would be easier and cleaner just use openpyxl by itself ^_^
python - add hyperlink to excel sheet created by pandas dataframe to_excel method - Stack Overflow
python - Retain hyperlinks in Pandas - Excel to dataframe - Stack Overflow
python - hyperlink in pandas (dataframe to excel) - Stack Overflow
python - how do I process an excel file with hyperlink/url in pandas? - Stack Overflow
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')
Probably you need a comma (,) instead of a semi-colon (;) in the formula. This is because Excel stores formulas in US-style syntax (see Non US Excel functions and syntax in the XlsxWriter docs).
When I run your formula through XlsxWriter I get an Excel warning about "We found a problem with some content in 'demo.xlsx'" and when I click on "yes" to recover the formula is zero, as your described.
Changing the semi-colon to a comma makes the program work without warning and as expected:
import xlsxwriter
workbook = xlsxwriter.Workbook('demo.xlsx')
worksheet = workbook.add_worksheet()
link = '=HYPERLINK(\"{0}/tr_events.php?triggerid={1}&eventid={2}\", \"{3}\")'.format('www.foo.com', 'abc', 'def', 'event1')
worksheet.write('A1', link)
# Or with a hyperlink format.
url_format = workbook.get_default_url_format()
worksheet.write('A2', link, url_format)
workbook.close()
Output:

Use xlwt which has a formula module which will store as a formula object in your dataframe.
You can then write this to excel with pandas using df.to_excel like so:
import xlwt
... # your other code here
link = '=HYPERLINK(\"{0}/tr_events.php?triggerid={1}&eventid={2}\"; \"{3}\")'.format(args.url, trigger_id,event['eventid'], event['name'])
excel_formatted = xlwt.Formula(link)
Then when this is passed to excel it should appear as the formula of whatever passed. I only tested it with the LEN() function but it worked fine.
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?
