Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hyperlink style in Openpyxl

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?

like image 598
Jeffrey Magedanz Avatar asked Sep 26 '15 21:09

Jeffrey Magedanz


People also ask

How do I style a cell in openpyxl?

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.

How do I change the color of openpyxl?

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()


2 Answers

You have to change style attribute

cell.style = "Hyperlink"
like image 100
Humberto Márquez Blanco Avatar answered Oct 03 '22 00:10

Humberto Márquez Blanco


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
like image 24
HHK Avatar answered Oct 03 '22 00:10

HHK