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

2024-10-03 00:23:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试在我的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()

Tags: 方法text文档maindefcelllocationexcel
3条回答
# 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)

试试这个:

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

使用xlsxwriter模块来完成它,因为它很简单,have a look at the documentation

# 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')

相关问题 更多 >