python-3.x - 使用 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)
有人知道如何做到这一点吗?
解决方案
重用函数从这个答案添加超链接,
首先,我们将形成“邮寄至链接”,然后将其作为超链接添加到文档中,就像任何其他超链接一样:-
#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')
推荐阅读
- c# - 行选择更改之前的 WinForms dataGridView 事件处理程序
- mysql - 如何使用角度和节点检查 if 条件下的服务器响应
- python-3.x - 未找到 python 模块中的意外行为
- attributes - HCL OneTest Data 中的类别、组和项目类型有什么区别?
- sql - 在 PostgreSQL 中透视表
- matrix - 用于直线和矩形之间转换的仿射变换矩阵
- javascript - 如何在 ADF 中编写内联 JavaScript
- c - 如何将 LZW 压缩文本写入 C 中的文件?
- android - Docker 上的 Android SDK for ARM64 (Raspberry Pi 4) 用于构建 APK
- javascript - 跨域请求阻止了 Django 和 React