【发布时间】:2020-11-20 04:02:55
【问题描述】:
在openpyxl中,你可以像这样设置一个超链接:
cell.hyperlink = r'..\somedir\somefile.txt'
但是,这不会应用您在 Excel 中设置超链接时获得的超链接样式。您可以应用带有蓝色文本和下划线的样式,但是当您打开文档时,访问过的超链接不会改变颜色。
有没有办法用 openpyxl 来指定一个超链接样式,就像在 Excel 中设置的超链接一样?
【问题讨论】:
在openpyxl中,你可以像这样设置一个超链接:
cell.hyperlink = r'..\somedir\somefile.txt'
但是,这不会应用您在 Excel 中设置超链接时获得的超链接样式。您可以应用带有蓝色文本和下划线的样式,但是当您打开文档时,访问过的超链接不会改变颜色。
有没有办法用 openpyxl 来指定一个超链接样式,就像在 Excel 中设置的超链接一样?
【问题讨论】:
你必须改变样式属性
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
【讨论】:
我使用了Font,它成功了。
from openpyxl.styles import Font
hyperlink = Font(underline='single', color='0563C1')
# ...
cell.font = hyperlink
应该有一个名为Hyperlink 的builtin sytle,但我没有设法让它工作......
【讨论】:
尝试像这样添加超链接样式
ft = Font()
ft.underline = 'single' # add single underline
ft.color = Color(rgb='000000FF') # add blue color
cell.font = ft
【讨论】:
这对我有用:
cell.value = '=HYPERLINK("{}", "{}")'.format('/my/unix/path/data.html', 'theData')
cell.style='Hyperlink'
其中 'theData' 是人们在单元格中看到的显示值。
【讨论】: