使用Python实现在Word中添加或删除超链接

2025-01-24 16:50

本文主要是介绍使用Python实现在Word中添加或删除超链接,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

《使用Python实现在Word中添加或删除超链接》在Word文档中,超链接是一种将文本或图像连接到其他文档、网页或同一文档中不同部分的功能,本文将为大家介绍一下Python如何实现在Word中添加或...

在Word文档中,超链接是一种将文本或图像连接到其他文档、网页或同一文档中不同部分的功能。通过添加超链接,用户可以轻松地导航到相关信息,从而增强文档的互动性和可读性。本文将介绍如何使用python在Word中添加超链接、或删除Word文档中的超链接

要实现通过Python操作Word文档,我们需要安装 Spire.Doc for Python 库。该库的pip安装命令如下:

pip install Spire.Doc

Python 在Word中添加超链接

Spire.Doc for Python 库提供了 AppendHyperlink() 方法来添加超链接,其中三个参数:

• link – 代表超链接地址

• text – 代表显示文本 (也可传入picture来为图片添加超链接)

• type – 代表超链接类型 (包括网页链接WebLink、邮件链接EMailLink、书签链接Bookmark、文件链接FileLink)

示例代码如下:

from spire.doc import *
from spire.doc.common import *

# 创建Word文档
doc = Document()

# 添加一节
section = doc.AddSection()

# 添加一个段落
paragraph = section.AddParagraph()

# 添加一个简单网页链接
paragraph.AppendHyperlink("https://ABCD.com/", "主页", HyperlinkType.WebLink)

# 添加换行符
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 添加一个邮箱链接
paragraph.AppendHyperlink("mailto:support@e-iceblue.com", "邮箱地址", HyperlinkType.EMailLink)

# 添加换行符
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 添加一个文档链接
filePath = "C:\\Users\\Administrator\\Desktop\\排名.xlsx"
paragraph.AppendHyperlink(filePath, "点击查看文件", HyperlinkType.FileLink)

# 添加换行符
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 添加一个新节并创建书签
section2 = doc.AddSection()
bookmarkParagrapg = section2.AddParagraph()
bookmarkParagrapg.AppendText("添加一个新段落")
start = bookmarkParagrapg.AppendBookmarkStart("书签")
bookmarkParagrapg.Items.Insert(0, start)
bookmarkParagrapg.AppenandroiddBookmarkEnd("书签")

# 链接到书签
paragraph.AppendHyperlink("书签", "点击跳转到文档指定位置", HyperlinkType.Bookmark)

# 添加换行符
paragraph.AppendBreak(BreakType.LineBreak)
paragraph.AppendBreak(BreakType.LineBreak)

# 添加一个图片超链接
image = "C:\\Users\\Administrator\\Desktop\\work1.jpg"
picture = paragraph.AppendPicture(image)
paragraph.AppendHyperlink("https://ABCD.com/", picture, HyperlinkType.WebLink)

# 保存文档
doc.SaveToFile("Word超链接.docx", FileFormat.Docx2019);
doc.Dispose()

生成文档:

使用Python实现在Word中添加或删除超链接

Python 删除Word中的超链接

要删除 Word 文档中的所有超链接,先用到了自定义方法 FindAllHyperlinks() 来查找文档中的所有超链接,然后再通过自定义方法 FlattenHyperlinks() 来扁平化超链接。

示例代码如下:

from spire.doc import *
from spire.doc.common import *

# 查找文档中的所有超链接
def FindAllHyperlinks(document):
    hyperlinks = []
    for i in range(document.Sections.Count):
        section = document.Sections.get_Item(i)
        for j in range(section.Body.ChildObjects.Count):
            sec = section.Body.ChildObjects.get_Item(j)
            if sec.DocumentObjectType == DocumentObjectType.Paragraph:
                for k in range((sec if isinstance(sec, Paragraph) else None).ChildObjects.Count):
                    para = (sec if isinstance(sec, Paragraph)
                            else None).ChildObjects.get_Item(k)
                    if para.DocumentObjectType == DocumentObjectType.Field:
                        field = para if isinstance(para, Field) else None
                        if field.Type == FieldType.FieldHyperlink:
                            hyperlinks.append(field)
    return hyperlinks

# 扁平化超链接域
def FlattenHyperlinks(field):
    ownerParaIndex = field.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(
        field.OwnerParagraph)
    fieldIndex = field.OwnerParagraph.ChildObjects.IndexOf(field)
    sepOwnerPara = field.Separator.OwnerParagraph
    sepOwnerParaIndex = field.Separator.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(
        field.Separator.OwnerParagraph)
    sepIndex = field.Separator.OwnerParagraph.ChildObjects.IndexOf(
        field.Separator)
    endIndex = field.End.OwnerParagraph.ChildObjects.IndexOf(field.End)
    endOwnerParaIndex = field.End.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(
        field.End.OwnerParagraph)

    FormatFieldResultText(field.Separator.OwnerParagraph.OwnerTextBody,
                           sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex)

    field.End.OwnerParagraph.ChildObjects.RemoveAt(endIndex)
    
    for i in range(sepOwnerParaIndex, ownerParaIndex - 1, -1):
        if i == sepOwnerParaIndex and i == ownerParaIndex:
            for j in range(sepIndex, fieldIndex - 1, -1):
                field.OwnerParagraph.ChildObjects.RemandroidoveAt(j)

        elif i == ownerParaIndex:
            for j in range(field.OwnerParagraph.ChildObjects.Count - 1, fieldIndex - 1, -1):
                field.OwnerParagraph.ChildObjects.RemoveAt(j)

    China编程    elif i == sepOwnerParaIndex:
            for j in range(sepIndex, -1, -1):
                sepOwnerPara.ChildObjects.RemoveAt(j)
        else:
            field.OwnerParagraph.OwnerTextBody.ChildObjects.RemoveAt(i)

# 将域转换为文本范围并清除文本格式
def FormatFieldResultText(ownerBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex):
    for i in range(sepOwnerParaIndex, endOwnerParaIndex + 1):
        para = ownerBody.ChildObjects[i] if isinstance(
            ownerBody.ChildObjects[i], Paragraph) else None
        if i == sepOwnerParaIndex and i == endOwnerParaIndex:
            for j in range(sepIndex + 1, endIndex):
               if isinstance(para.ChildObjects[j], TextRange):
                 FormatText(para.ChildObjects[j])

        elif i == sepOwnerParaIndex:
            for j in range(sepIndex + 1, para.ChildObjects.Count):
                if isinstance(para.ChildObjects[j], TextRange):
                  FormatText(para.ChildObjects[j])
        elif i == endOwnerParaIndex:
            for j in range(0, endIndex):
               if isinstance(para.ChildObjects[j], TextRange):
                 FormatText(para.ChildObjects[j]js)
        else:
            for j, unusedItem in enumerate(para.ChildObjects):
                if isinstance(para.ChildObjects[j], TextRange):
                  FormatText(para.ChildObjects[j])

# 设置文本样式
def FormatText(trwww.chinasem.cn):
    tr.CharacterFormat.TextColor = Color.get_Black()
    tr.CharacterFormat.UnderlineStyle = UnderlineStyle.none

# 加载Word文档
doc = Document()
doc.LoadFromFile("Word超链接.docx")

# 获取所有超链接
hyperlinks = FindAllHyperlinks(doc)

# 扁平化超链接
for i in range(len(hyperlinks) - 1, -1, -1):
    FlattenHyperlinks(hyperlinks[i])

# 保存文件
doc.SaveToFile("删除超链接.docx", FileFormat.Docx)
doc.Close()

生成文件:

使用Python实现在Word中添加或删除超链接

到此这篇关于使用Python实现在Word中添加或删除超链接的文章就介绍到这了,更多相关Python Word添加或删除超链接内容请搜索编程China编程(www.chinasem.cn)以前的文章或继续浏览下面的相关文章希望大家以后多多支持China编程(www.chinasem.cn)!

这篇关于使用Python实现在Word中添加或删除超链接的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1153211

相关文章

IDEA中Git版本回退的两种实现方案

《IDEA中Git版本回退的两种实现方案》作为开发者,代码版本回退是日常高频操作,IntelliJIDEA集成了强大的Git工具链,但面对reset和revert两种核心回退方案,许多开发者仍存在选择... 目录一、版本回退前置知识二、Reset方案:整体改写历史1、IDEA图形化操作(推荐)1.1、查看提

python dict转换成json格式的实现

《pythondict转换成json格式的实现》本文主要介绍了pythondict转换成json格式的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下... 一开始你变成字典格式data = [ { 'a' : 1, 'b' : 2, 'c编程' : 3,

Ollama Python 使用小结

《OllamaPython使用小结》Ollama提供了PythonSDK,使得开发者能够在Python环境中轻松集成和使用本地运行的模型进行自然语言处理任务,具有一定的参考价值,感兴趣的可以了解一... 目录安装 python SDK启动本地服务使用 Ollama 的 Python SDK 进行推理自定义客

使用Python实现文本转语音(TTS)并播放音频

《使用Python实现文本转语音(TTS)并播放音频》在开发涉及语音交互或需要语音提示的应用时,文本转语音(TTS)技术是一个非常实用的工具,下面我们来看看如何使用gTTS和playsound库将文本... 目录什么是 gTTS 和 playsound安装依赖库实现步骤 1. 导入库2. 定义文本和语言 3

Android自定义Scrollbar的两种实现方式

《Android自定义Scrollbar的两种实现方式》本文介绍两种实现自定义滚动条的方法,分别通过ItemDecoration方案和独立View方案实现滚动条定制化,文章通过代码示例讲解的非常详细,... 目录方案一:ItemDecoration实现(推荐用于RecyclerView)实现原理完整代码实现

C语言实现两个变量值交换的三种方式

《C语言实现两个变量值交换的三种方式》两个变量值的交换是编程中最常见的问题之一,以下将介绍三种变量的交换方式,其中第一种方式是最常用也是最实用的,后两种方式一般只在特殊限制下使用,需要的朋友可以参考下... 目录1.使用临时变量(推荐)2.相加和相减的方式(值较大时可能丢失数据)3.按位异或运算1.使用临时

python中字符串拼接的几种方法及优缺点对比详解

《python中字符串拼接的几种方法及优缺点对比详解》在Python中,字符串拼接是常见的操作,Python提供了多种方法来拼接字符串,每种方法有其优缺点和适用场景,以下是几种常见的字符串拼接方法,需... 目录1. 使用 + 运算符示例:优缺点:2. 使用&nbsjsp;join() 方法示例:优缺点:3

java streamfilter list 过滤的实现

《javastreamfilterlist过滤的实现》JavaStreamAPI中的filter方法是过滤List集合中元素的一个强大工具,可以轻松地根据自定义条件筛选出符合要求的元素,本文就来... 目录1. 创建一个示例List2. 使用Stream的filter方法进行过滤3. 自定义过滤条件1. 定

使用C语言实现交换整数的奇数位和偶数位

《使用C语言实现交换整数的奇数位和偶数位》在C语言中,要交换一个整数的二进制位中的奇数位和偶数位,重点需要理解位操作,当我们谈论二进制位的奇数位和偶数位时,我们是指从右到左数的位置,本文给大家介绍了使... 目录一、问题描述二、解决思路三、函数实现四、宏实现五、总结一、问题描述使用C语言代码实现:将一个整

如何使用Python实现一个简单的window任务管理器

《如何使用Python实现一个简单的window任务管理器》这篇文章主要为大家详细介绍了如何使用Python实现一个简单的window任务管理器,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起... 任务管理器效果图完整代码import tkinter as tkfrom tkinter i