如何使用 openpyxl 从图像添加到另一个单元格的超链接?

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

我已通过 openpyxl 将图像添加到 xlsx 文件中。现在,我还想向同一图像添加超链接(类似于向单元格添加超链接,但我需要将其添加到图像),这样当您单击它时,它将调用/引用该单元格中的另一个单元格同一张纸或同一文件的另一张纸中。

我的添加图像的代码运行良好,但我无法想出一个代码来添加超链接。

我试过这个:

img.hyperlink = '=HYPERLINK("{}", "{}")'.format('A1', '')
python-3.x openpyxl
1个回答
0
投票

我已经尝试过使用 Openpyxl 来完成此操作,但认为它并不容易实现。

如果对您有用,下面的示例将使用 Xlwings 实现结果,但需要安装 Windows 和 Excel。
此示例创建一个包含单个图像的工作表(我使用的图像大约等于标准单元格的高度且不大于标准单元格),并启用指向同一张工作表上的单元格“D1”的超链接。
即使图像最初锚定到单元格“B2”,如果移动图像,超链接仍将指向单元格“D1”。

import xlwings as xw

sheet = 'Sheet1'

pic_location = 'B2'  # Location the image will be anchored to
link_cell = 'D1'  # Cell the image hyperlink will link to

### Hyperlink, i.e. local sheet and cell in the format "'Sheet1'!D1"
LinkAddress = f"'{sheet}'!{link_cell}"  
### Mouse over description of Hyperlink if required
LinkDescription = f"Jump to Cell {link_cell}"


with xw.App(visible=False) as app:
    wb = xw.Book()
    ws = wb.sheets[0]
    
    ### Name the new Sheet to the same as used in the hyperlink
    ws.title = sheet

    ### Add the image to the sheet at cell 'B2' 
    link_pic = ws.pictures.add(
        r'C:\Temp\pic1.jpg',  # Image location. Full path and image name
        left=ws.range(f'{pic_location}').left,
        top=ws.range(f'{pic_location}').top
    )

    ### Add hyperlink to the image just inserted
    ws.api.Hyperlinks.Add(
        Anchor=link_pic.api.ShapeRange.Item(1),
        Address="",  # This entry is needed but not used so set as shown
        SubAddress=LinkAddress,
        ScreenTip=LinkDescription
    )

    wb.save('hyperlink_image.xlsx')
© www.soinside.com 2019 - 2024. All rights reserved.