是的,我们能做到。Referenceimport 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')

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐