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

enyaitl3  于 4个月前  发布在  Python
关注(0)|答案(1)|浏览(84)

我已经通过openpyxl在xlsx文件中添加了一个图像。现在,我还想在同一个图像中添加一个超链接(类似于在单元格中添加超链接,但我需要将其添加到图像中),这样当您单击它时,它将调用/引用同一工作表中的另一个单元格或同一文件的另一个工作表中的另一个单元格。
我添加图像的代码工作得很好,但我不能想出一个代码来添加超链接到它。
我试过这个:

img.hyperlink = '=HYPERLINK("{}", "{}")'.format('A1', '')

字符串

lhcgjxsq

lhcgjxsq1#

我曾经尝试过用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')

字符串

相关问题