[尝试使用Python的docx模块在MS Word文档中添加超链接(用于电子邮件)。
我到处搜索(官方文档,StackOverflow,Google),但一无所获。
我想做类似的事情:
from docx import Document
document = Document()
p = document.add_paragraph('A plain paragraph')
p.add_hyperlink(mail_to:[email protected], Subject: The plain paragraph)
任何人都知道如何做到这一点?
重新使用功能以从此answer添加超链接,
首先,我们将形成“邮件链接”,然后像其他任何超链接一样,将其作为超链接添加到文档中:-
#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="[email protected]"
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')