Openpyxl 中的超链接样式

问题描述 投票:0回答:6

在openpyxl中,你可以像这样设置超链接:

cell.hyperlink = r'..\somedir\somefile.txt'

但是,这不会应用在 Excel 中设置超链接时获得的超链接样式。您可以应用带有蓝色文本和下划线的样式,但是当您打开文档时,访问的超链接不会改变颜色。

openpyxl 有没有办法指定超链接样式,其工作方式类似于 Excel 中的超链接集?

python openpyxl
6个回答
7
投票

你必须改变样式属性

cell.style = "Hyperlink"

3
投票
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

1
投票

我使用了

Font
,它起作用了。

from openpyxl.styles import Font
hyperlink = Font(underline='single', color='0563C1')
# ...
cell.font = hyperlink

应该有一个名为 Hyperlink

内置 sytle
,但我还没有设法让它工作......


0
投票

尝试添加这样的超链接样式

ft = Font()
ft.underline = 'single'    # add single underline
ft.color = Color(rgb='000000FF')  # add blue color
cell.font = ft

0
投票

这对我有用:

cell.value = '=HYPERLINK("{}", "{}")'.format('/my/unix/path/data.html', 'theData')
cell.style='Hyperlink'

其中“theData”是人们在单元格中看到的显示值。


0
投票

据我所知,cell.style =“Hyperlink”应用了Excel中定义的超链接样式。如果覆盖单元格样式,“链接”属性就会丢失。

这对我有用(链接到不同的工作表):

更改 Excel 中的链接样式:

在电子表格的单元格中插入链接。选择该单元格后,在“主页”选项卡上,右键单击“超链接样式”并选择“修改”。这会将新样式应用于工作簿中的所有链接。

openpyxl:

cell.value = f'=HYPERLINK("#'TOC'!A{target_toc_cell}", "{table_name} (返回目录)")' cell.style = "超链接"

© www.soinside.com 2019 - 2024. All rights reserved.