Insert DataTable to Word file in C# and VB.NET

Table can be constructed programmatically in a variety of ways with GemBox.Document.

Following example shows how simple it is to construct a table from a DataTable.

For importing DataTable or any other data to a document, see Mail Merge example.

Insert DataTable Screenshot
using System.Data;
using GemBox.Document;
using GemBox.Document.Tables;

class Program
    static void Main()
        // If using Professional version, put your serial key below.

        DocumentModel document = new DocumentModel();

        int tableRowCount = %RowCount%;
        int tableColumnCount = %ColumnCount%;

        // Initialize DataTable
        DataTable dt = new DataTable();

        for (int i = 0; i < tableColumnCount; i++)

        for (int i = 0; i < tableRowCount; i++)
            DataRow row = dt.NewRow();
            for (int j = 0; j < tableColumnCount; j++)
                row[j] = string.Format("Cell {0}-{1}", i + 1, j + 1);

        // Initialize Table
        Table table = new Table(document, tableRowCount, tableColumnCount,
            (int rowIndex, int columnIndex) => new TableCell(document, new Paragraph(document, dt.Rows[rowIndex][columnIndex].ToString())));

        table.TableFormat.PreferredWidth = new TableWidth(100, TableWidthUnit.Percentage);

        document.Sections.Add(new Section(document, table));

        document.Save("Insert DataTable.%OutputFileType%");
Imports System.Data
Imports GemBox.Document
Imports GemBox.Document.Tables

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.

        Dim document As DocumentModel = New DocumentModel

        Dim tableRowCount As Integer = %RowCount%
        Dim tableColumnCount As Integer = %ColumnCount%

        ' Initialize DataTable
        Dim dt As New DataTable()

        For i As Integer = 0 To tableColumnCount - 1

        For i As Integer = 0 To tableRowCount - 1
            Dim row As DataRow = dt.NewRow()
            For j As Integer = 0 To tableColumnCount - 1
                row(j) = String.Format("Cell {0}-{1}", i + 1, j + 1)

        ' Initialize Table
        Dim table As New Table(document, tableRowCount, tableColumnCount,
                               Function(rowIndex As Integer, columnIndex As Integer) New TableCell(document, New Paragraph(document, dt.Rows(rowIndex)(columnIndex).ToString())))

        table.TableFormat.PreferredWidth = New TableWidth(100, TableWidthUnit.Percentage)

        document.Sections.Add(New Section(document, table))

        document.Save("Insert DataTable.%OutputFileType%")

    End Sub

End Module

Check next example or download examples from GitHub.