Mail merge html formatted text from database to word document

3.4k Views Asked by At

I am doing a mail merge using a dataset that is coming from a SQL database. The data that I am retrieving is stored in the database with some HTML markups in it, example:

One of my merge fields contains this text:

<ul><li><strong>Bullet Title 1</strong>Bullet content 1.</li><li><strong>Bullet Title 2</strong>Bullet content 2.</li></ul>

Another one of my merge fields contains this text:

<strong>List of employees</strong><br />First Name< br />Second Name<br />Third Name

For now I'm using Spire.Doc, but when the document renders, the fields show the html tags instead of rendering the formatted text.

Below is the code I'm using:

   Public Shared Sub FieldMerge(ByVal ds As DataSet, ByRef doc As Document)

        '**********************************
        'Merging
        '**********************************
        Dim fieldNames As New List(Of String)()
        Dim fieldValues As New List(Of String)()


        For Each dtcolumn As DataColumn In ds.Tables(0).Columns
            'Add the values to the list of string
            fieldNames.Add(dtcolumn.ColumnName)

            '**** THIS TEXT COULD HAVE SOME HTML TAGS - HOW TO RENDER THIS IN THE MERGE FIELD???? *****'
            fieldValues.Add(ds.Tables(0).Rows(0)(dtcolumn.ColumnName).ToString)

        Next

        Dim fieldNamesArray As String() = fieldNames.ToArray()
        Dim fieldValuesArray As String() = fieldValues.ToArray()

        'Execute the merge
        doc.MailMerge.Execute(fieldNamesArray, fieldValuesArray)


    End Sub

How can I accomplish the merge field to show the formatted text instead of the html tags? Any advices will be much appreciated.

1

There are 1 best solutions below

0
On

Here is how you can do that with GemBox.Document:

Public Shared Sub FieldMerge(ByVal ds As DataSet, ByRef doc As DocumentModel)
    AddHandler doc.MailMerge.FieldMerging,
        Sub(sender, e)
            If e.FieldName = "MyField" Then
                e.Field.Content.End.LoadText(e.Value.ToString(), LoadOptions.HtmlDefault)
                e.Inline = Nothing
            End If
        End Sub

    doc.MailMerge.Execute(ds.Tables(0))
End Sub

That sample shows how you can customize a mail merge process by handling FieldMerging event. The merge field with a "MyField" name should receive a HTML formatted string, so the "MyField" column in your DataTable should have HTML text.
Also as you can see the mail merge can take DataTable as a data source. You can find mail merge example here, and mail merge documentation here.

Also I think you'll find the following article interesting: How to insert HTML and RTF content during the mail merge process