Shankar Kumar
Shankar Kumar

Reputation: 2357

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

I am trying add hyperlinking functionality in my Excel documents by being able to click on a cell and it will take me to another part of the Excel document. I have code below that should take me to cell A21 when I click on A1. The code executes fine, but when I click on the link, a window pops up saying "Cannot open the specified file." Is there a problem with the way I'm referencing the cell? Or is there a better way to accomplish this?

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()

Upvotes: 1

Views: 1812

Answers (3)

James McComb
James McComb

Reputation: 11

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

Upvotes: 0

Jagadeesh Kanchi
Jagadeesh Kanchi

Reputation: 11

Use xlsxwriter module to do it as simple as it is, 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')

Upvotes: 1

NorthCat
NorthCat

Reputation: 9937

Try this:

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

Upvotes: 2

Related Questions