Skip to sidebar Skip to content
Ipercube Technical
Jack of all trades, master of none
Date: Time: - Stardate:
Welcome, Log in by clicking  Here!
SS64
MDN
Stack
Code
GitHub
Wiki
Convert
V Studio
  • Home
  • VB Functions
    • Access Functions
    • Assembly Info
    • Color/Image Functions
    • Data Table Functions
    • Email Functions
    • Active Directory Functions
    • LDAP Functions
    • Excel Functions
    • Logging Functions
    • Source Code Retrieval
    • String Functions
    • Sql Functions
    • Object Utilities Functions
    • System and Utilities
    • Utility Forms
  • VB Classes
    • Environment Variables Helper
  • ABAP
    • ABAP Reports
    • ABAP HTTP Functions
Ipercube Technical
  • Home
  • VB Functions
    • Access Functions
    • Assembly Info
    • Color/Image Functions
    • Data Table Functions
    • Email Functions
    • Active Directory Functions
    • LDAP Functions
    • Excel Functions
    • Logging Functions
    • Source Code Retrieval
    • String Functions
    • Sql Functions
    • Object Utilities Functions
    • System and Utilities
    • Utility Forms
  • VB Classes
    • Environment Variables Helper
  • ABAP
    • ABAP Reports
    • ABAP HTTP Functions

Data Import/Export – Write Datatable to Sheet

Writes the contents of a DataTable to the specified Excel worksheet starting from a given cell.

VB
    Public Sub xlWriteDatatable2Sheet(dt As Data.DataTable, 
                                      sheet As Worksheet, 
                                      Optional upperLeftCell As String = "A1")

        If dt Is Nothing OrElse dt.Columns.Count = 0 Then Exit Sub

        Dim startRow As Integer = sheet.Range(upperLeftCell).Row
        Dim startCol As Integer = sheet.Range(upperLeftCell).Column
        Dim currentRow As Integer = startRow

        With sheet
            ' Write headers
            For c As Integer = 0 To dt.Columns.Count - 1
                .Cells(currentRow, startCol + c).Value = dt.Columns(c).ColumnName
            Next

            ' Write data rows
            For r As Integer = 0 To dt.Rows.Count - 1
                currentRow += 1
                For c As Integer = 0 To dt.Columns.Count - 1
                    Try
                        Dim value = dt.Rows(r)(c)
                        .Cells(currentRow, startCol + c).Value = If(IsDBNull(value), String.Empty, value)
                        '.Cells(currentRow, startCol + c).Value = If(IsDBNull(value), String.Empty, Convert.ChangeType(value, dc.DataType))
                    Catch
                        .Cells(currentRow, startCol + c).Value = String.Empty
                    End Try
                Next
            Next
        End With

    End Sub

Posted by ipercube


© 2026 Ipercube Design