Jake
Jake

Reputation: 313

Create Excel Hyperlinks in Python

I am using win32com to modify an Excel spreadsheet (Both read and edit at the same time) I know there are other modules out there that can do one or the other but for the application I am doing I need it read and processed at the same time.

The final step is to create some hyperlinks off of a path name. Here is an Example of what I have so far:

import win32com.client


excel = r'I:\Custom_Scripts\Personal\Hyperlinks\HyperlinkTest.xlsx'

xlApp = win32com.client.Dispatch("Excel.Application")
workbook = xlApp.Workbooks.Open(excel)
worksheet = workbook.Worksheets("Sheet1")


for xlRow in xrange(1, 10, 1):
    a = worksheet.Range("A%s"%(xlRow)).Value
    if a == None:
        break
    print a

workbook.Close()

I found some code for reading Hyperlinks using win32com:

sheet.Range("A8").Hyperlinks.Item(1).Address

but not how to set hyperlinks

Can someone assist me?

Upvotes: 0

Views: 9549

Answers (1)

SiHa
SiHa

Reputation: 8411

Borrowing heavily from this question, as I couldn't find anything on SO to link to as a duplicate...

This code will create a Hyperlink in cells A1:A9

import win32com.client

excel = r'I:\Custom_Scripts\Personal\Hyperlinks\HyperlinkTest.xlsx'

xlApp = win32com.client.Dispatch("Excel.Application")
workbook = xlApp.Workbooks.Open(excel)
worksheet = workbook.Worksheets("Sheet1") 

for xlRow in xrange(1, 10, 1):
    worksheet.Hyperlinks.Add(Anchor = worksheet.Range('A{}'.format(xlRow)),
                             Address="http://www.microsoft.com",
                             ScreenTip="Microsoft Web Site",
                             TextToDisplay="Microsoft")
workbook.Save()
workbook.Close()

And here is a link to the Microsoft Documentation for the Hyperlinks.Add() method.

Upvotes: 2

Related Questions