Word .NET庫(kù)組件Spire.Doc系列教程(31): 添加,替換和刪除 Word 書(shū)簽
Spire.Doc for .NET是一個(gè)專(zhuān)業(yè)的Word .NET庫(kù),設(shè)計(jì)用于幫助開(kāi)發(fā)人員高效地開(kāi)發(fā)創(chuàng)建、閱讀、編寫(xiě)、轉(zhuǎn)換和打印任何來(lái)自.NET( C#, VB.NET, ASP.NET)平臺(tái)的Word文檔文件的功能。
本系列教程將為大家?guī)?lái)Spire.Doc for .NET在使用過(guò)程中的各類(lèi)實(shí)際操作,本篇文章介紹了如何在Word中添加,替換和刪除 Word 書(shū)簽。>>下載Spire.Doc最新試用版體驗(yàn)
C# 添加,替換和刪除 Word 書(shū)簽
書(shū)簽可以用于標(biāo)識(shí)指定文本的位置。在Word文檔中,我們可以對(duì)指定內(nèi)容添加書(shū)簽,修改或替換現(xiàn)有書(shū)簽的內(nèi)容,如果不再需要一個(gè)書(shū)簽了,也可以很容易的刪除它。
添加書(shū)簽
Spire.Doc提供了一個(gè)類(lèi)Paragraph,在該類(lèi)中有兩個(gè)方法AppendBookmarkStart (string name) 和 AppendBookmarkEnd (string name) 可以幫助我們添加書(shū)簽到指定的段落,其中BookmarkStart代表書(shū)簽的起始位置,BookmarkEnd代表書(shū)簽的結(jié)束位置。
//加載文檔 Document document = new Document(); document.LoadFromFile(@"向日葵.docx"); //添加書(shū)簽 “bookmark” Section section = document.Sections[0]; section.Paragraphs[5].AppendBookmarkStart("bookmark"); section.Paragraphs[6].AppendBookmarkEnd("bookmark"); //保存文檔 document.SaveToFile("添加書(shū)簽.docx", FileFormat.Docx);
替換書(shū)簽
BookmarkNavigator用于導(dǎo)航到書(shū)簽,通過(guò)它我們可以獲取,替換和刪除指定書(shū)簽的內(nèi)容。此外,Spire.Doc還支持在替換書(shū)簽時(shí)保留原書(shū)簽的格式,僅需要將ReplaceBookmarkContent (TextBodyPart bodyPart, bool isKeepSourceFirstParaFormat, bool saveFormatting) 方法中的相關(guān)參數(shù)設(shè)置為true。
//加載文檔 Document document = new Document(); document.LoadFromFile(@"添加書(shū)簽.docx"); //添加一個(gè)section到文檔 Section sec = document.AddSection(); //添加兩個(gè)段落到section sec.AddParagraph().AppendText("Welcome Back, "); sec.AddParagraph().AppendText("Friend! "); //獲取段落內(nèi)容 ParagraphBase firstReplacementParagraph = sec.Paragraphs[0].Items.FirstItem as ParagraphBase; ParagraphBase lastReplacementParagraph = sec.Paragraphs[sec.Paragraphs.Count - 1].Items.LastItem as ParagraphBase; TextBodySelection selection = new TextBodySelection(firstReplacementParagraph, lastReplacementParagraph); TextBodyPart part = new TextBodyPart(selection); //移動(dòng)到書(shū)簽 “bookmark”, 刪除它的內(nèi)容并保留格式 BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); bookmarkNavigator.MoveToBookmark("bookmark", true, true); bookmarkNavigator.DeleteBookmarkContent(true); //用新添加段落的內(nèi)容替換掉原書(shū)簽的內(nèi)容并保留格式 bookmarkNavigator.ReplaceBookmarkContent(part, true, true); //移除section并保存文檔 document.Sections.Remove(sec); document.SaveToFile("替換書(shū)簽.docx");
刪除書(shū)簽
在Spire.Doc中,每一個(gè)Word文檔都含有一個(gè)書(shū)簽的集合,我們可以通過(guò)Document類(lèi)的Bookmarks屬性來(lái)訪問(wèn)該集合,并可以通過(guò)該集合的FindByName(string name)方法來(lái)查找指定的書(shū)簽,然后將其刪除。
//加載文檔 Document document = new Document(); document.LoadFromFile(@"添加書(shū)簽.docx"); Bookmark bookmark = document.Bookmarks.FindByName("bookmark"); //移除書(shū)簽 “bookmark” document.Bookmarks.Remove(bookmark); //保存文檔 document.SaveToFile("刪除書(shū)簽.docx", FileFormat.Docx);
推薦閱讀:【想要快速完成文檔格式轉(zhuǎn)換嗎?Spire系列組件格式轉(zhuǎn)換完整攻略來(lái)啦!】
*購(gòu)買(mǎi)Spire.Doc正版授權(quán)的朋友可以點(diǎn)擊哦~~