none
How to Populate merge fields RRS feed

  • Question

  • Hi,

    I’m using the WordprocessingDocument method to create a word document from a template file.  I’ve this working correctly, however, I’m not sure how to loop through the MERGEFIELDS in my template document and populate them with content.

    I'm using the .Net 4.0 framework.

    Could someone please provide an example of how I could achieve this?

    Thanks in advance.
    Monday, November 12, 2012 11:41 AM

Answers

  • Hi alcoalex

    Is there special reason for you to use Mergefields rather than bookmarks or content controls as the data "targets"?

    Mergefields weren't designed for this task and using them could be very complicated - more so than bookmarks or content controls...


    Cindy Meister, VSTO/Word MVP, my blog

    Tuesday, November 13, 2012 8:58 AM
    Moderator

All replies

  • Hi alcoalex,

    Thanks for posting in the MSDN Forum.

    As usual, merge Word document to the other will use following code:

        Public Function MergeDocument(ByVal WPD As WordprocessingDocument) As Boolean
            Dim Result As Boolean = False
            Dim altChunkId As String = "AltChunkId1"
            Dim MP As MainDocumentPart = WPD.MainDocumentPart
            Dim chunk As AlternativeFormatImportPart
            Dim altChunk As AltChunk
    
            Try
                chunk = MP.AddAlternativeFormatImportPart( _
                    AlternativeFormatImportPartType.WordprocessingML, altChunkId)
                Using FS As FileStream = File.Open("C:\*\*.docx", FileMode.Open)
                    chunk.FeedData(FS)
                End Using
                altChunk = New AltChunk
                altChunk.Id = altChunkId
                altChunk.AltChunkProperties = New AltChunkProperties
                altChunk.AltChunkProperties.MatchSource = New MatchSource
                altChunk.AltChunkProperties.MatchSource.Val = _
                    OnOffValue.FromBoolean(True)
                MP.Document.Body.InsertAfter(altChunk, MP.Document.Body.Elements( _
                                             Of Paragraph)().Last())
                MP.Document.Save()
                Result = True
            Catch ex As Exception
                SetLog(ex.Message, OXULogType.FATAL)
            End Try
    
            MergeDocument = Result
        End Function

    I hope it can help you.

    Have a good day,

    Tom


    Tom Xu [MSFT]
    MSDN Community Support | Feedback to us

    Tuesday, November 13, 2012 5:04 AM
    Moderator
  • Hi alcoalex

    Is there special reason for you to use Mergefields rather than bookmarks or content controls as the data "targets"?

    Mergefields weren't designed for this task and using them could be very complicated - more so than bookmarks or content controls...


    Cindy Meister, VSTO/Word MVP, my blog

    Tuesday, November 13, 2012 8:58 AM
    Moderator