当前位置: 首页 > 面试题库 >

使用python-docx在MSWord中添加超链接

滕成双
2023-03-14
问题内容

我正在尝试使用docx适用于Python的模块在MS Word文档中添加超链接。

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

我想做类似的事情:

from docx import Document

document = Document()

p = document.add_paragraph('A plain paragraph having some ')
p.add_hyperlink('Link to my site', target="http://supersitedelamortquitue.fr")

任何人都知道如何做到这一点?


问题答案:

是的,我们可以做到。参考

import docx
from docx.enum.dml import MSO_THEME_COLOR_INDEX

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


document = docx.Document()
p = document.add_paragraph('A plain paragraph having some ')
add_hyperlink(p, 'Link to my site', "http://supersitedelamortquitue.fr")
document.save('demo_hyperlink.docx')


 类似资料:
  • 问题内容: 我想在使用创建的PDF中添加超链接,这样我单击一些文本示例,“单击此处”将重定向到URL。我尝试使用和,但是如何添加呢? 问题答案: 要添加使用以下代码

  • 我有工作代码将图像插入到DOCX模板中(使用docxtpl提供的Jinja模板格式),但是当图像插入到文档正文时,图像无法在标题中呈现。文档中的插入点显示消息“read error”。

  • 有什么想法如何添加一个超链接在一个网页上使用这个库? 我发现了这个问题:如何使用pdfbox在内容中设置超链接,但这不起作用。 我只想在pdf文件的第一页添加一个超链接。 我更喜欢在页面底部添加以URL为中心的超链接。但目前任何建议都有帮助

  • 点击下图信息窗中的字段值“中国工商银行”,将打开中国工商银行的网站 亿景智图中,不需要编程就可以实现这样的效果,将字段值按以下形式组织即可:<a href=网址>网站标识</a>,例如 <a href='http://www.icbc.com.cn/icbc/'>中国工商银行</a>,需要注意的是,url 上的引号必须是英文字符,单引号或是双引号均可。 如果需要在新窗口中打开链接,在url后面空格

  • 问题内容: 如何在SWT表列中添加超链接?我正在使用org.eclipse.swt.widgets.Table类。 没有使用TableViewer,JFace有什么方法吗? 我尝试过这种方式,但无法正常工作(不显示超链接)。 问题答案: 是的,那肯定是可能的。为此,您必须实现(也可能是和)。 如果使用正确的方法,则更容易…

  • 问题内容: 我有一个日志文件,其中使用python记录了一些测试命令及其状态(通过/失败)。现在,我希望测试命令不应写为简单文本,而应写为超链接。这样,当我单击它们时,将打开另一个链接到它们的文件。 例如: 现在,我希望写在logfile.log中的CommandName应该是文件TestCommand.log的超链接,以便当我单击CommandName时,文件TestCommand.log会打开