Replace bookmark text in Word file using Open XML SDK

前端 未结 11 2000
眼角桃花
眼角桃花 2020-12-01 08:24

I assume v2.0 is better... they have some nice \"how to:...\" examples but bookmarks don\'t seem to act as obviously as say a Table... a bookmark is defined by two

11条回答
  •  一整个雨季
    2020-12-01 08:56

    Here is how i do it and VB to add/replace text between bookmarkStart and BookmarkEnd.

     
            - 
              forbund_kort 
              
    
    
    
    Imports DocumentFormat.OpenXml.Packaging
    Imports DocumentFormat.OpenXml.Wordprocessing
    
        Public Class PPWordDocx
    
            Public Sub ChangeBookmarks(ByVal path As String)
                Try
                    Dim doc As WordprocessingDocument = WordprocessingDocument.Open(path, True)
                     'Read the entire document contents using the GetStream method:
    
                    Dim bookmarkMap As IDictionary(Of String, BookmarkStart) = New Dictionary(Of String, BookmarkStart)()
                    Dim bs As BookmarkStart
                    For Each bs In doc.MainDocumentPart.RootElement.Descendants(Of BookmarkStart)()
                        bookmarkMap(bs.Name) = bs
                    Next
                    For Each bs In bookmarkMap.Values
                        Dim bsText As DocumentFormat.OpenXml.OpenXmlElement = bs.NextSibling
                        If Not bsText Is Nothing Then
                            If TypeOf bsText Is BookmarkEnd Then
                                'Add Text element after start bookmark
                                bs.Parent.InsertAfter(New Run(New Text(bs.Name)), bs)
                            Else
                                'Change Bookmark Text
                                If TypeOf bsText Is Run Then
                                    If bsText.GetFirstChild(Of Text)() Is Nothing Then
                                        bsText.InsertAt(New Text(bs.Name), 0)
                                    End If
                                    bsText.GetFirstChild(Of Text)().Text = bs.Name
                                End If
                            End If
    
                        End If
                    Next
                    doc.MainDocumentPart.RootElement.Save()
                    doc.Close()
                Catch ex As Exception
                    Throw ex
                End Try
            End Sub
    
        End Class
    

提交回复
热议问题