繁体   English   中英

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

[英]Error when using Python to create hyperlink within a worksheet in Excel

我试图通过单击单元格在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()

尝试这个:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM