首页 > 解决方案 > 使用 python-docx 在 MSWord 中添加超链接(电子邮件)

问题描述

尝试使用 Python 的 docx 模块在 MS Word 文档中添加超链接(用于电子邮件)。

我到处搜索(官方文档、StackOverflow、Google),但一无所获。

我想做类似的事情:

from docx import Document

document = Document()   

p = document.add_paragraph('A plain paragraph')
p.add_hyperlink(mail_to:Joe_doe@email.com, Subject: The plain paragraph)

有人知道如何做到这一点吗?

标签: python-3.xdocxpython-docx

解决方案


重用函数从这个答案添加超链接,

首先,我们将形成“邮寄至链接”,然后将其作为超链接添加到文档中,就像任何其他超链接一样:-

#Necessary imports
from docx import Document
#Styling 
from docx.enum.dml import MSO_THEME_COLOR_INDEX
document=Document()
p = document.add_paragraph('A plain paragraph')

def add_hyperlink(paragraph, text, url):
    # This gets access to the document.xml.rels file and gets a new relation id value
    part = paragraph.part
    r_id = part.relate_to(url, docx.opc.constants.RELATIONSHIP_TYPE.HYPERLINK, is_external=True)

    # Create the w:hyperlink tag and add needed values
    hyperlink = docx.oxml.shared.OxmlElement('w:hyperlink')
    hyperlink.set(docx.oxml.shared.qn('r:id'), r_id, )

    # Create a w:r element and a new w:rPr element
    new_run = docx.oxml.shared.OxmlElement('w:r')
    rPr = docx.oxml.shared.OxmlElement('w:rPr')

    # Join all the xml elements together add add the required text to the w:r element
    new_run.append(rPr)
    new_run.text = text
    hyperlink.append(new_run)

    # Create a new Run object and add the hyperlink into it
    r = paragraph.add_run ()
    r._r.append (hyperlink)

    # A workaround for the lack of a hyperlink style (doesn't go purple after using the link)
    # Delete this if using a template that has the hyperlink style in it
    r.font.color.theme_color = MSO_THEME_COLOR_INDEX.HYPERLINK
    r.font.underline = True

    return hyperlink

#Define recipient and subject    
to_mail="John_doe@email.com"
subject="The plain paragraph"

mail_to_link=f"mailto:{to_mail}?Subject={subject}" 

#Adding the mail to link as any other hyperlink
add_hyperlink(p, 'Please Mail Us', mail_to_link)
document.save('mail_to_link_demo.docx')

推荐阅读