使用Python處理Word文檔書(shū)簽

在處理長(zhǎng)篇 Word 文檔時(shí),書(shū)簽(Bookmark)是一種非常有用的導(dǎo)航和定位工具。書(shū)簽允許開(kāi)發(fā)者標(biāo)記文檔中的特定位置或內(nèi)容區(qū)域,從而實(shí)現(xiàn)快速訪(fǎng)問(wèn)、內(nèi)容替換和動(dòng)態(tài)文檔生成等功能。
本文將介紹如何使用 Python 和 Spire.Doc for Python 庫(kù)在 Word 文檔中執(zhí)行各種書(shū)簽操作,包括創(chuàng)建書(shū)簽、提取書(shū)簽文本、替換書(shū)簽內(nèi)容、在書(shū)簽位置插入圖片和表格,以及刪除書(shū)簽等實(shí)用技術(shù)。
環(huán)境準(zhǔn)備
首先,需要安裝 Spire.Doc for Python 庫(kù):
pip install Spire.Doc
安裝完成后,即可開(kāi)始使用書(shū)簽相關(guān)的 API 進(jìn)行 Word 文檔處理。
什么是書(shū)簽及其應(yīng)用場(chǎng)景
書(shū)簽是 Word 文檔中的一種標(biāo)記機(jī)制,可以為文檔的特定位置或內(nèi)容區(qū)域命名。常見(jiàn)的應(yīng)用場(chǎng)景包括:
- 文檔導(dǎo)航:為重要章節(jié)或段落添加書(shū)簽,方便用戶(hù)快速跳轉(zhuǎn)
- 模板填充:在文檔模板中預(yù)設(shè)書(shū)簽,程序運(yùn)行時(shí)動(dòng)態(tài)替換為實(shí)際內(nèi)容
- 內(nèi)容提取:快速提取文檔中特定標(biāo)記區(qū)域的內(nèi)容
- 動(dòng)態(tài)文檔生成:根據(jù)業(yè)務(wù)需求在指定位置插入文本、圖片或表格
創(chuàng)建書(shū)簽
創(chuàng)建書(shū)簽是最基本的操作。在 Spire.Doc 中,可以通過(guò) AppendBookmarkStart 和 AppendBookmarkEnd 方法來(lái)定義書(shū)簽的起始和結(jié)束位置。
以下示例演示如何創(chuàng)建簡(jiǎn)單書(shū)簽和嵌套書(shū)簽:
from spire.doc import *
from spire.doc.common import *
def CreateBookmarkInDocument():
# 創(chuàng)建 Word 文檔
document = Document()
# 添加新節(jié)
section = document.AddSection()
# 添加標(biāo)題段落
paragraph = section.AddParagraph()
txtRange = paragraph.AppendText("以下示例演示如何在 Word 文檔中創(chuàng)建書(shū)簽。")
txtRange.CharacterFormat.Italic = True
# 添加簡(jiǎn)單書(shū)簽
section.AddParagraph()
paragraph = section.AddParagraph()
txtRange = paragraph.AppendText("簡(jiǎn)單書(shū)簽示例")
txtRange.CharacterFormat.TextColor = Color.get_CornflowerBlue()
paragraph.ApplyStyle(BuiltinStyle.Heading2)
section.AddParagraph()
paragraph = section.AddParagraph()
paragraph.AppendBookmarkStart("SimpleBookmark")
paragraph.AppendText("這是一個(gè)簡(jiǎn)單書(shū)簽的內(nèi)容。")
paragraph.AppendBookmarkEnd("SimpleBookmark")
# 添加嵌套書(shū)簽
section.AddParagraph()
paragraph = section.AddParagraph()
txtRange = paragraph.AppendText("嵌套書(shū)簽示例")
txtRange.CharacterFormat.TextColor = Color.get_CornflowerBlue()
paragraph.ApplyStyle(BuiltinStyle.Heading2)
section.AddParagraph()
paragraph = section.AddParagraph()
paragraph.AppendBookmarkStart("Root")
txtRange = paragraph.AppendText(" 根級(jí)別內(nèi)容 ")
txtRange.CharacterFormat.Italic = True
paragraph.AppendBookmarkStart("Level1")
txtRange = paragraph.AppendText(" 第一級(jí)嵌套內(nèi)容 ")
txtRange.CharacterFormat.Italic = True
txtRange.CharacterFormat.TextColor = Color.get_DarkSlateGray()
paragraph.AppendBookmarkStart("Level2")
txtRange = paragraph.AppendText(" 第二級(jí)嵌套內(nèi)容 ")
txtRange.CharacterFormat.Italic = True
txtRange.CharacterFormat.TextColor = Color.get_DimGray()
paragraph.AppendBookmarkEnd("Level2")
paragraph.AppendBookmarkEnd("Level1")
paragraph.AppendBookmarkEnd("Root")
# 保存文檔
document.SaveToFile("CreateBookmark.docx", FileFormat.Docx)
document.Close()
CreateBookmarkInDocument()
結(jié)果文檔:

在上述代碼中,AppendBookmarkStart 和 AppendBookmarkEnd 方法成對(duì)使用,通過(guò)相同的書(shū)簽名稱(chēng)來(lái)標(biāo)識(shí)書(shū)簽的范圍。嵌套書(shū)簽允許在一個(gè)書(shū)簽內(nèi)部包含其他書(shū)簽,形成層次結(jié)構(gòu)。
提取書(shū)簽文本
提取書(shū)簽內(nèi)容是一項(xiàng)常見(jiàn)需求,特別是在需要從大型文檔中獲取特定信息時(shí)??梢允褂?BookmarksNavigator 類(lèi)來(lái)定位并提取書(shū)簽內(nèi)容。
from spire.doc import *
from spire.doc.common import *
def ExtractBookmarkText():
# 加載文檔
doc = Document()
doc.LoadFromFile("CreateBookmark.docx")
# 創(chuàng)建書(shū)簽導(dǎo)航器實(shí)例
navigator = BookmarksNavigator(doc)
# 移動(dòng)到指定書(shū)簽
navigator.MoveToBookmark("SimpleBookmark")
# 獲取書(shū)簽內(nèi)容
textBodyPart = navigator.GetBookmarkContent()
# 遍歷書(shū)簽內(nèi)容項(xiàng)以提取文本
text = ''
for i in range(textBodyPart.BodyItems.Count):
item = textBodyPart.BodyItems.get_Item(i)
if isinstance(item, Paragraph):
for j in range(item.ChildObjects.Count):
childObject = item.ChildObjects.get_Item(j)
if isinstance(childObject, TextRange):
text += childObject.Text
print(f"提取的書(shū)簽文本:{text}")
# 將文本寫(xiě)入文件
with open("ExtractedText.txt", "w", encoding="utf-8") as f:
f.write(text)
doc.Close()
ExtractBookmarkText()
BookmarksNavigator 類(lèi)的 MoveToBookmark 方法用于定位到指定名稱(chēng)的書(shū)簽,GetBookmarkContent 方法返回書(shū)簽的內(nèi)容對(duì)象。通過(guò)遍歷內(nèi)容對(duì)象中的子項(xiàng),可以提取出純文本內(nèi)容。
替換書(shū)簽內(nèi)容
在實(shí)際應(yīng)用中,經(jīng)常需要用新內(nèi)容替換書(shū)簽位置的原有內(nèi)容。這在文檔模板填充場(chǎng)景中非常有用。
from spire.doc import *
from spire.doc.common import *
def ReplaceBookmarkContent():
# 加載文檔
doc = Document()
doc.LoadFromFile("CreateBookmark.docx")
# 定位到書(shū)簽
bookmarkNavigator = BookmarksNavigator(doc)
bookmarkNavigator.MoveToBookmark("SimpleBookmark")
# 用新內(nèi)容替換書(shū)簽內(nèi)容
bookmarkNavigator.ReplaceBookmarkContent("這是替換后的新內(nèi)容。", False)
# 保存文檔
doc.SaveToFile("ReplaceBookmarkContent.docx", FileFormat.Docx)
doc.Close()
ReplaceBookmarkContent()
ReplaceBookmarkContent 方法的第一個(gè)參數(shù)是要替換的新內(nèi)容,第二個(gè)參數(shù)控制是否保留原有格式。設(shè)置為 False 表示不保留原有格式,使用新內(nèi)容的默認(rèn)格式。
在書(shū)簽位置插入圖片
除了文本替換,還可以在書(shū)簽位置插入圖片,這對(duì)于生成包含圖表或徽標(biāo)的文檔非常有用。
from spire.doc import *
from spire.doc.common import *
def InsertImageAtBookmark():
# 加載文檔
doc = Document()
doc.LoadFromFile("CreateBookmark.docx")
# 創(chuàng)建書(shū)簽導(dǎo)航器實(shí)例
bn = BookmarksNavigator(doc)
# 查找名為 "SimpleBookmark" 的書(shū)簽
bn.MoveToBookmark("SimpleBookmark", True, True)
# 添加臨時(shí)節(jié)和段落
section0 = doc.AddSection()
paragraph = section0.AddParagraph()
# 在段落中添加圖片
picture = paragraph.AppendPicture("./SampleImage.png")
# 在書(shū)簽位置插入該段落
bn.InsertParagraph(paragraph)
# 移除臨時(shí)節(jié)
doc.Sections.Remove(section0)
# 保存文檔
doc.SaveToFile("InsertImageAtBookmark.docx", FileFormat.Docx)
doc.Close()
InsertImageAtBookmark()
此方法的核心思路是先創(chuàng)建一個(gè)包含圖片的段落,然后使用 InsertParagraph 方法將該段落插入到書(shū)簽位置。最后移除臨時(shí)創(chuàng)建的節(jié),保持文檔結(jié)構(gòu)整潔。
在書(shū)簽位置插入表格
表格是 Word 文檔中常用的元素,可以在書(shū)簽位置動(dòng)態(tài)插入表格來(lái)展示結(jié)構(gòu)化數(shù)據(jù)。
from spire.doc import *
from spire.doc.common import *
def ReplaceBookmarkWithTable():
# 加載文檔
doc = Document()
doc.LoadFromFile("CreateBookmark.docx")
# 創(chuàng)建表格
table = Table(doc, True)
# 準(zhǔn)備表格數(shù)據(jù)
rowsCount = 4
colsCount = 5
data = [
["姓名", "首都", "大洲", "面積", "人口"],
["阿根廷", "布宜諾斯艾利斯", "南美洲", "2777815", "32300003"],
["玻利維亞", "拉巴斯", "南美洲", "1098575", "7300000"],
["巴西", "巴西利亞", "南美洲", "8511196", "150400000"]
]
# 重置表格單元格
table.ResetCells(rowsCount, colsCount)
# 填充表格數(shù)據(jù)
for i in range(rowsCount):
for j in range(colsCount):
table.Rows[i].Cells[j].AddParagraph().AppendText(data[i][j])
# 定位到書(shū)簽
navigator = BookmarksNavigator(doc)
navigator.MoveToBookmark("SimpleBookmark")
# 創(chuàng)建 TextBodyPart 實(shí)例并添加表格
part = TextBodyPart(doc)
part.BodyItems.Add(table)
# 用表格替換書(shū)簽內(nèi)容
navigator.ReplaceBookmarkContent(part)
# 保存文檔
doc.SaveToFile("ReplaceWithTable.docx", FileFormat.Docx)
doc.Close()
ReplaceBookmarkWithTable()
在這個(gè)示例中,首先創(chuàng)建一個(gè) Table 對(duì)象并填充數(shù)據(jù),然后將表格添加到 TextBodyPart 對(duì)象中,最后使用 ReplaceBookmarkContent 方法將表格插入到書(shū)簽位置。這種方法可以靈活地插入各種復(fù)雜內(nèi)容。
刪除書(shū)簽
當(dāng)不再需要某個(gè)書(shū)簽時(shí),可以將其從文檔中刪除。需要注意的是,刪除書(shū)簽不會(huì)刪除其包含的內(nèi)容,只會(huì)移除書(shū)簽標(biāo)記本身。
from spire.doc import *
from spire.doc.common import *
def RemoveBookmark():
# 加載文檔
document = Document()
document.LoadFromFile("CreateBookmark.docx")
# 通過(guò)名稱(chēng)獲取書(shū)簽
bookmark = document.Bookmarks["SimpleBookmark"]
# 刪除書(shū)簽(保留內(nèi)容)
document.Bookmarks.Remove(bookmark)
# 保存文檔
document.SaveToFile("RemoveBookmark.docx", FileFormat.Docx)
document.Close()
RemoveBookmark()
如果需要同時(shí)刪除書(shū)簽及其內(nèi)容,可以先使用 ReplaceBookmarkContent 方法清空內(nèi)容,然后再刪除書(shū)簽標(biāo)記。
實(shí)用技巧
獲取文檔中的所有書(shū)簽
在處理未知結(jié)構(gòu)的文檔時(shí),可能需要先獲取所有書(shū)簽的名稱(chēng)列表:
from spire.doc import *
def GetAllBookmarks():
doc = Document()
doc.LoadFromFile("CreateBookmark.docx")
# 遍歷所有書(shū)簽
for bookmark in doc.Bookmarks:
print(f"書(shū)簽名稱(chēng):{bookmark.Name}")
doc.Close()
GetAllBookmarks()
檢查書(shū)簽是否存在
在操作書(shū)簽之前,最好先檢查書(shū)簽是否存在,以避免運(yùn)行時(shí)錯(cuò)誤:
def CheckBookmarkExists(doc, bookmarkName):
for bookmark in doc.Bookmarks:
if bookmark.Name == bookmarkName:
return True
return False
總結(jié)
本文介紹了使用 Python 和 Spire.Doc for Python 庫(kù)在 Word 文檔中進(jìn)行書(shū)簽操作的多種技術(shù),包括:
- 創(chuàng)建簡(jiǎn)單書(shū)簽和嵌套書(shū)簽
- 提取書(shū)簽中的文本內(nèi)容
- 替換書(shū)簽內(nèi)容為新的文本
- 在書(shū)簽位置插入圖片
- 在書(shū)簽位置插入表格
- 刪除書(shū)簽標(biāo)記
書(shū)簽功能為 Word 文檔自動(dòng)化處理提供了強(qiáng)大的支持,特別適用于文檔模板填充、動(dòng)態(tài)內(nèi)容生成和信息提取等場(chǎng)景。通過(guò)合理使用書(shū)簽,可以顯著提高文檔處理的效率和靈活性。
在實(shí)際開(kāi)發(fā)中,可以根據(jù)具體需求組合使用這些操作,構(gòu)建更加復(fù)雜的文檔自動(dòng)化解決方案。例如,可以創(chuàng)建包含多個(gè)書(shū)簽的文檔模板,然后根據(jù)業(yè)務(wù)數(shù)據(jù)動(dòng)態(tài)填充各個(gè)書(shū)簽位置的內(nèi)容,實(shí)現(xiàn)批量文檔生成。
以上就是使用Python處理Word文檔書(shū)簽的詳細(xì)內(nèi)容,更多關(guān)于Python處理Word書(shū)簽的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
- 使用python-docx在word文檔中查找書(shū)簽,并在書(shū)簽處寫(xiě)入數(shù)據(jù)方式
- 通過(guò)Python實(shí)現(xiàn)在Word中添加和刪除書(shū)簽的操作
- Python自動(dòng)化辦公之從Excel/Word處理到瀏覽器操控的全面指南
- Python文檔處理之實(shí)現(xiàn)自動(dòng)刪除Word中帶指定底紋顏色的內(nèi)容
- Python文件解析之Excel/Word/PDF的解析、處理、預(yù)覽與下載
- python基于python-docx庫(kù)自動(dòng)化處理Word文檔的完整指南
- 使用Python實(shí)現(xiàn)Word文檔處理自動(dòng)化的操作方法
- 從基礎(chǔ)到進(jìn)階詳解Python處理Word文檔的完全指南
相關(guān)文章
Python實(shí)現(xiàn)的檢測(cè)網(wǎng)站掛馬程序
這篇文章主要介紹了Python實(shí)現(xiàn)的檢測(cè)網(wǎng)站掛馬程序,需要的朋友可以參考下2014-11-11
Python+Tkinter編寫(xiě)一個(gè)批量IP地址歸屬地查詢(xún)
這篇文章主要為大家詳細(xì)介紹了Python如何結(jié)合Tkinter編寫(xiě)一個(gè)批量IP地址歸屬地查詢(xún),文中的示例代碼講解詳細(xì),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2025-11-11
利用Python將數(shù)值型特征進(jìn)行離散化操作的方法
今天小編就為大家分享一篇利用Python將數(shù)值型特征進(jìn)行離散化操作的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11
pycharm不以pytest方式運(yùn)行,想要切換回普通模式運(yùn)行的操作
這篇文章主要介紹了pycharm不以pytest方式運(yùn)行,想要切換回普通模式運(yùn)行的操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-09-09
Python腳本簡(jiǎn)單實(shí)現(xiàn)打開(kāi)默認(rèn)瀏覽器登錄人人和打開(kāi)QQ的方法
這篇文章主要介紹了Python腳本簡(jiǎn)單實(shí)現(xiàn)打開(kāi)默認(rèn)瀏覽器登錄人人和打開(kāi)QQ的方法,涉及Python針對(duì)瀏覽器及應(yīng)用程序的相關(guān)操作技巧,代碼非常簡(jiǎn)單實(shí)用,需要的朋友可以參考下2016-04-04
Pycharm中如何關(guān)掉python console
這篇文章主要介紹了Pycharm中如何關(guān)掉python console,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-10-10
Python使用ftfy修復(fù)Unicode編碼問(wèn)題的具體教程
在處理文本時(shí),常常會(huì)遇到字符被錯(cuò)誤解碼、符號(hào)被替換成奇怪的符號(hào)等亂碼問(wèn)題,ftfy是一個(gè)專(zhuān)為修復(fù)各種文本編碼錯(cuò)誤而設(shè)計(jì)的 Python 工具,所以本文給大家介紹了Python使用ftfy修復(fù)Unicode編碼問(wèn)題的具體教程,需要的朋友可以參考下2025-06-06

