使用Python在Microsoft Word中添加超链接

3
我已经搜索了几个小时了,但是找不到一个可以让我使用Python向Word文档添加超链接的库。在我的理想世界里,我将能够使用Python操纵Word文档,向脚注添加链接,这些链接指向内部文档。但是Python-docx似乎没有此功能。
这可以分为两个问题。1)有没有办法使用Python向Word文档添加超链接?2)有没有办法使用Python操纵Word文档中的脚注?
有人知道如何实现这一点或其中任何部分吗?

你可以使用python-docx从(正确的)xml创建docx文档。如果你创建了一个带有超链接的word文档,你可以解压它,查看正确的标记,并将其用作模板来操作现有文档。 - Marcin
除了Marcin的评论之外,如果您查看并挖掘此处,可能会有所帮助。不确定这是否已合并到主分支。 - disflux
2个回答

2

使用win32com包可以添加超链接:

import win32com.client

#connect to Word (start it if it isn't already running)
wordapp = win32com.client.Dispatch("Word.Application")

#add a new document
doc = wordapp.Documents.Add()

#add some text and turn it into a hyperlink
para = doc.Paragraphs.Add()
para.Range.Text = "Adding hyperlinks in Microsoft word using python"
doc.Hyperlinks.Add(Anchor=para.Range,  Address="https://dev59.com/apLea4cB1Zd3GeqP6L1a")
#In theory you should be able to also pass in a TextToDisplay argument to the above call but I haven't been able to get this to work
#The workaround is to insert the link text into the document first and then convert it into a hyperlink

1
# How to insert hyperlinks into an existing MS Word document using win32com:

# Use the same call as in the example above to connect to Word:
wordapp = win32com.client.Dispatch("Word.Application")

# Open the input file where you want to insert the hyperlinks:
wordapp.Documents.Open("my_input_file.docx")

# Select the currently active document
doc = wordapp.ActiveDocument

# For my application, I want to replace references to identifiers in another 
# document with the general format of "MSS-XXXX", where X is any digit, with 
# hyperlinks to local html pages that capture the supporting details...

# First capture the entire document's content as text
docText = doc.Content.text

# Search for all identifiers that match the format criteria in the document:
mss_ids_to_link = re.findall('MSS-[0-9]+', docText)

# Now loop over all the identifier strings that were found, construct the link
# address for each html page to be linked, select the desired text where I want
# to insert the hyperlink, and then apply the link to the correct range of 
# characters:
for linkIndex in range(len(mss_ids_to_link)):
    current_string_to_link = mss_ids_to_link[linkIndex]
    link_address           = html_file_pathname + \
                             current_string_to_link + '.htm'
    if wordapp.Selection.Find.Execute(FindText=current_string_to_link, \
                                      Address=link_address) == True:
        doc.Hyperlinks.Add(Anchor=wordapp.Selection.Range, \
                           Address=link_address)

# Save off the result:
doc.SaveAs('my_input_file.docx')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接