Create Excel Hyperlinks in Python

末鹿安然 提交于 2019-12-23 05:52:20

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/39791441/create-excel-hyperlinks-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!