在現代辦公環境中,閱讀或編輯較長篇幅的Word文檔時,想要在文檔中某處或幾處留下標記,方便日後查找、修改時,需要在相對應的文檔位置插入書籤。那對開發者而言,在C#或VB.NET語言環境中,如何來快速、簡單的插入書籤呢,我分享一下我的經驗。這裡我用到了一個E-iceblue公司發布的一款免費的Word元件(Free Spire.Doc for .NET),方法很簡單,如下:
步驟一:初始化Document實例並載入Word文件
Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\中国梦.docx ");
步驟二:於第七段末和第八段間插入書籤,命名書籤為「C#.bookmark」
##
Section section = document.Sections[0]; section.Paragraphs[7].AppendBookmarkStart("C#.bookmark"); section.Paragraphs[8].AppendBookmarkEnd("C#.bookmark ");
步驟三:儲存檔案
document.SaveToFile("Bookmark.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Bookmark.docx");
C
##
using System;using Spire.Doc;using Spire.Doc.Documents;namespace WordBookmark { class Bookmark { static void Main(string[] args) { //Load Document Document document = new Document(); document.LoadFromFile(@"C:\Users\Administrator\Desktop\中国梦.docx "); //Insert Bookmark Section section = document.Sections[0]; section.Paragraphs[7].AppendBookmarkStart(".NETFramework"); section.Paragraphs[8].AppendBookmarkEnd(".NETFramework"); //Save and Launch document.SaveToFile("Bookmark.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Bookmark.docx"); } } }
VB.NET:
Imports System Imports Spire.Doc Imports Spire.Doc.Documents Namespace WordBookmark Class Bookmark Private Shared Sub Main(ByVal args() As String) 'Load Document Dim document As Document = New Document document.LoadFromFile("C:\Users\Administrator\Desktop\中国梦.docx ") 'Insert Bookmark Dim section As Section = document.Sections(0) section.Paragraphs(7).AppendBookmarkStart(".NETFramework") section.Paragraphs(8).AppendBookmarkEnd(".NETFramework") 'Save and Launch document.SaveToFile("Bookmark.docx", FileFormat.Docx) System.Diagnostics.Process.Start("Bookmark.docx") End Sub End Class End Namespace
同樣的,撤銷書籤也可以參考執行我下面的動作
##步驟一:載入需要撤銷書籤的Word文件
#
Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\中国梦(书签).docx");
步驟二:撤銷已有書籤
doc.Bookmarks.RemoveAt(0);
#步驟三:儲存檔案
doc.SaveToFile("Remove Bookmark.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Remove Bookmark.docx");
#如圖,原本插入書籤的段落已撤銷書籤
完整程式碼如下C
#:
using Spire.Doc;namespace Removing { class Program { static void Main(string[] args) { //Load Document Document doc = new Document(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\中国梦(书签).docx "); //Remove Bookmark doc.Bookmarks.RemoveAt(0); //Save and Launch doc.SaveToFile("Remove Bookmark.docx", FileFormat.Docx); System.Diagnostics.Process.Start("Remove Bookmark.docx"); } } }
Imports Spire.Doc Namespace Removing Class Program Private Shared Sub Main(ByVal args() As String) 'Load Document Dim doc As Document = New Document doc.LoadFromFile("C:\Users\Administrator\Desktop\中国梦(书签).docx ") 'Remove Bookmark doc.Bookmarks.RemoveAt(0) 'Save and Launch doc.SaveToFile("Remove Bookmark.docx", FileFormat.Docx) System.Diagnostics.Process.Start("Remove Bookmark.docx") End Sub End Class End Namespace
以上是C#中VB.NET為Word文件新增/撤銷書籤的實例的詳細內容。更多資訊請關注PHP中文網其他相關文章!