【问题标题】:how to insert bookmark in word using c#/VB.NET如何使用 c#/VB.NET 在 word 中插入书签
【发布时间】:2011-07-15 21:23:40
【问题描述】:

我正在尝试使用 C# 在 word 文档中添加书签,但它不起作用,我在 msdn 文档和互联网上都找不到任何帮助。这是我正在尝试做的事情。

我正在阅读 word 文档,然后在该文档中搜索关键字,然后将该文本转换为超链接,效果很好。现在,我想将该文本创建到书签而不是超链接。我在 C# 中完成所有这些操作

【问题讨论】:

    标签: c# .net vb.net ms-word bookmarks


    【解决方案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)
    

    【讨论】:

    • 如何在word文档中的特定位置(使用左、右)添加这个书签?
    【解决方案2】:

    您需要掌握 Open XML SDK。它没有很好的记录......

    我很久以前发布了关于将图像插入 Word 文档的文章。根本不是一回事,但你永远不知道,你可能会找到一些让你开始的指针......

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

    【讨论】:

    • 感谢分享,但我想使用 Word API。以下代码使我的应用程序崩溃。如果我添加超链接,则以下代码有效,但如果我只想添加书签,则它不起作用。我已经评论了超链接代码。 '_doc.Hyperlinks.Add(_doc.Range(pos, len + pos), Address, _ ' SubAddress, ScreenTip, TextToDisplay, _ ' Target) bookmarkName = _doc.Range(pos, len + pos).Text Dim rng As Object = _doc.Range(pos, len + pos) _doc.Bookmarks.Add(bookmarkName, rng)
    • 好的,我已经成功了。令人困惑的是它正在崩溃,因此 .NET API 中存在错误。我注意到书签名称中不能有空格。我删除了空格,现在它正在工作。顺便感谢您的帮助。
    • 太棒了。我建议您将您的修复作为答案发布,然后接受它(回答并接受您自己的问题是完全可以的),因为它将帮助其他人在未来遇到同样的问题。
    猜你喜欢
    • 2012-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多