通过VB.NET在Word表中的MailMerge数据

时间:2012-06-27 07:05:44

标签: vb.net interop mailmerge

wrdMergeFields.Add(wrdSelection.Range, "ProductName")

上面的代码基本上显示了合并期间Word文档中不同页面中的所有productName。

请帮我如何将数据放入表格中。我必须为我的ProductName,AccountNo,OutBalance,AccountName等编写多个代码。我的问题是我不知道如何将它们放在表格中。

1 个答案:

答案 0 :(得分:0)

如果您对第三方库感兴趣以解决您的问题,可以试试我们的GemBox.Document组件。

以下是VB.NET代码示例(如何通过从代码创建模板文档并从文件加载):

' Use the component in free mode.
ComponentInfo.SetLicense("FREE-LIMITED-KEY")

' Define DataTable with two columns: 'Name' and 'Surname', and fill it with some data.
' You don't have to do this if you already have a DataTable instance.
Dim dataTable = New DataTable("People")
dataTable.Columns.Add(New DataColumn("Name", GetType(String)))
dataTable.Columns.Add(New DataColumn("Surname", GetType(String)))
dataTable.Rows.Add("John", "Doe")
dataTable.Rows.Add("Fred", "Nurk")
dataTable.Rows.Add("Hans", "Meier")
dataTable.Rows.Add("Ivan", "Horvat")

' Create and save a template document. 
' You don't have to do this if you already have a template document.
' This code is only provided as a reference how template document should look like.
Dim document = New DocumentModel()
document.Sections.Add(
    New Section(document,
        New Table(document,
            New TableRow(document,
                New TableCell(document,
                    New Paragraph(document, "Name")),
                New TableCell(document,
                    New Paragraph(document, "Surname"))),
            New TableRow(document,
                New TableCell(document,
                    New Paragraph(document,
                        New Field(document, FieldType.MergeField, "RangeStart:People"),
                        New Field(document, FieldType.MergeField, "Name"))),
                New TableCell(document,
                    New Paragraph(document,
                        New Field(document, FieldType.MergeField, "Surname"),
                        New Field(document, FieldType.MergeField, "RangeEnd:People")))))))
document.Save("TemplateDocument.docx", SaveOptions.DocxDefault)

' Load a template document.
document = DocumentModel.Load("TemplateDocument.docx", LoadOptions.DocxDefault)

' Mail merge template document with DataTable.
' Important: DataTable.TableName and RangeStart/RangeEnd merge field names must match.
document.MailMerge.ExecuteRange(dataTable)

' Save the mail merged document.
document.Save("Document.docx", SaveOptions.DocxDefault)

' Open the documents with MS Word.
Process.Start("TemplateDocument.docx")
Process.Start("Document.docx")