GemBox.Document is a .NET component that enables you to read, write, edit, convert, and print document files from your .NET applications using one simple API.

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 examples.

Insert DataTable Screenshot

See the full code below, use Run Example to execute.

using System;
using System.Data;
using GemBox.Document;
using GemBox.Document.Tables;

class Sample
    static void Main(string[] args)
        // If using Professional version, put your serial key below.

        DocumentModel document = new DocumentModel();

        int tableRowCount = 10;
        int tableColumnCount = 5;

        // 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.docx");
Imports System
Imports System.Data
Imports GemBox.Document
Imports GemBox.Document.Tables

Module Samples

    Sub Main()

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

        Dim document As DocumentModel = New DocumentModel

        Dim tableRowCount As Integer = 10
        Dim tableColumnCount As Integer = 5

        ' 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.docx")

    End Sub

End Module

Check next sample.