In openpyxl, you can set a hyperlink like this:
cell.hyperlink = r'..\somedir\somefile.txt'
However, this does not apply the hyperlink style that you would get when setting a hyperlink in Excel. You can apply a style with blue text and underlining, but when you open the document, visited hyperlinks do not change color.
Is there any way with openpyxl to specify a hyperlink style that works like a hyperlink set within Excel?
To change a style property of a cell, first you either have to copy the existing style object from the cell and change the value of the property or you have to create a new style object with the desired settings. Then, assign the new style object to the cell. Save this answer. Show activity on this post.
OpenPyXL gives you a class called PatternFill that you can use to change a cell's background color. The PatternFill class takes in the following arguments (defaults included below): patternType=None. fgColor=Color()
You have to change style attribute
cell.style = "Hyperlink"
import openpyxl
from openpyxl.styles import Font, Color, colors
#...
# alternative 1: set hyperlink property to cell
def link_1(cell, link, display=None):
cell.hyperlink = link
cell.font = Font(u='single', color=colors.BLUE)
if display is not None:
cell.value = display
# alternative 2: use Excel formula HYPERLINK
def link_2(cell, link, display='link'):
cell.value = '=HYPERLINK("%s", "%s")' % (link, display)
cell.font = Font(u='single', color=colors.BLUE)
# examples
link_1(ws['B2'], '#sheet3!A1', 'link_text') # internal link
link_2(ws['B3'], '#sheet3!A1', 'link_text') # internal link
link_1(ws['B4'], 'https://www.google.com/', 'Google') # web link
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With