how to insert bookmark in word using c#/VB.NET

*爱你&永不变心* 提交于 2019-12-23 17:51:48

问题


I am trying to add bookmarks in word document using C# but it doesn't work and I can't find any help neither in msdn documentation nor on internet. Here is how I am trying to do.

I am reading word documents and then search a keyword in that document and then I convert that text to a hyperlink and that works great. Now, I want to create that text to a bookmark instead of hyperlink. I am doing all this in C#


回答1:


Dim _wordApp As ApplicationClass
Dim _doc As Document
Dim pos, len As Integer
Dim reg As Regex
Dim bookmarkName As String
Dim rng As Object
Dim search As String = "Some Text to search"

Dim nullobj As Object = System.Reflection.Missing.Value
Dim isReadOnly As Object = False
_wordApp = New ApplicationClass()

'open the word document
_doc = _wordApp.Documents.Open(fileName, isReadOnly, nullobj, nullobj, nullobj, _
     nullobj, nullobj, nullobj, nullobj, nullobj, nullobj, _
     nullobj, nullobj, nullobj, nullobj, nullobj)

    _wordApp.Visible = False


' keyword that you want to search
reg = New Regex(search)
' find the text in word file
Dim m As Match = reg.Match(_doc.Range.Text, 0)
pos = m.Index

' start is the starting position of the token in the content...
len = search.Length
' select the text
rng = _doc.Range(pos, len + pos)

bookmarkName = "MyBookmarkName"
_doc.Bookmarks.Add(bookmarkName, rng)



回答2:


You need to get to grips with the Open XML SDK. It's not well documented...

I posted some significant time ago about inserting images into Word documents. Not the same thing at all, but you never know, you might find some pointers to get you started...

HowTo: Insert an image into a Word document and display it using OpenXML



来源:https://stackoverflow.com/questions/6713289/how-to-insert-bookmark-in-word-using-c-vb-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!