使用Python在Excel工作表中创建超链接时出错

1 投票
3 回答
1759 浏览
提问于 2025-04-18 11:45

我想在我的Excel文档中添加超链接功能,也就是说,当我点击一个单元格时,它能带我到Excel文档的另一个部分。我下面的代码应该能让我在点击A1时跳转到A21。代码运行得很好,但是当我点击链接时,弹出一个窗口说“无法打开指定的文件”。我在引用单元格的方式上有问题吗?还是说有更好的方法来实现这个功能?

from win32com.client import Dispatch
excel = Dispatch('Excel.Application')

def main():
    CreateLink()

def CreateLink():
    cell_location = excel.Worksheets(1).Cells(1,1)
    cell_destination = excel.Worksheets(1).Cells(21,1)
    cell_text = "Cell A21"
    excel.Worksheets(1).Hyperlinks.Add(Anchor=cell_location, Address=cell_destination, TextToDisplay=cell_text)

if __name__ == '__main__':
    main()

3 个回答

0

在编程中,有时候我们需要让程序做一些重复的事情,比如计算、处理数据等。为了让程序更高效,我们可以使用一个叫做“循环”的东西。循环就像是一个指令,让程序不停地重复执行某些操作,直到满足特定的条件为止。

想象一下,你在做一个简单的任务,比如数数。如果你要从1数到10,你可以一个一个地数,但这会很麻烦。使用循环,你可以告诉程序:“从1开始,一直数到10,每次加1。”这样,程序就会自动帮你完成这个任务,而不需要你手动去数。

循环有很多种类型,比如“for循环”和“while循环”。“for循环”适合当你知道要重复多少次的时候,而“while循环”则适合当你不知道要重复多少次,只要满足某个条件就继续执行。

总之,循环是编程中一个非常重要的工具,它可以让我们的代码更加简洁和高效。通过使用循环,我们可以节省时间和精力,让程序自动完成重复的工作。

# Make sure you include single quotes when you reference another sheet in a Workbook hyperlink.

# example code to link the same cell on two different worksheet

import win32com.client as win32com

output_filename = 'MyExcelWorkbook.xlsx'
excel = win32com.gencache.EnsureDispatch('Excel.Application')
wb    = excel.Workbooks.Open(output_filename)

worksheet1name = wb.Worksheets(1).Name
worksheet2name = wb.Worksheets(2).Name
ws_out         = wb.Worksheets.(worksheet1name)

for rowIndex in range(numRows):
    rangeString = 'A' + str(rowIndex)
    cell_destination = '\'' + sheet2name + '\'' + '!' + 'A' + str(rowIndex)
    ws_out.Hyperlinks.Add(Anchor=ws_out.Range(rangeString), Address='', SubAddress=cell_destination)
1

可以使用 xlsxwriter 这个模块来简单地完成这个任务,你可以查看一下它的文档

# Link to a cell on the current worksheet.
worksheet.write_url('A1',  'internal:Sheet2!A1')

# Link to a cell on another worksheet.
worksheet.write_url('A2',  'internal:Sheet2!A1:B2')

# Worksheet names with spaces should be single quoted like in Excel.
worksheet.write_url('A3',  "internal:'Sales Data'!A1")

# Link to another Excel workbook.
worksheet.write_url('A4', r'external:c:\temp\foo.xlsx')

# Link to a worksheet cell in another workbook.
worksheet.write_url('A5', r'external:c:\foo.xlsx#Sheet2!A1')

# Link to a worksheet in another workbook with a relative link.
worksheet.write_url('A7', r'external:..\foo.xlsx#Sheet2!A1')

# Link to a worksheet in another workbook with a network link.
worksheet.write_url('A8', r'external:\\NET\share\foo.xlsx')
2

试试这个:

def CreateLink():
    excel.Worksheets(1).Cells(1,1).Value = '=HYPERLINK(A21,"Cell A21")'

撰写回答