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