Skip to content

Instantly share code, notes, and snippets.

@arisawali2014
Created June 5, 2020 06:27
Show Gist options
  • Save arisawali2014/90e1e46dd52cfd2f44e89a1eada4f48b to your computer and use it in GitHub Desktop.
Save arisawali2014/90e1e46dd52cfd2f44e89a1eada4f48b to your computer and use it in GitHub Desktop.
VB.Net DataTable to CSV
Private Function dtTableToCSV(dt As DataTable, filename As String, Optional headers As Boolean = True, Optional delim As String = ",")
Dim txt As String
Dim fileloc As String = filename + ".csv"
If File.Exists(fileloc) Then
File.Delete(fileloc)
End If
Dim n = 0
If headers = True Then
For Each column As DataColumn In dt.Columns
If n = 0 Then
txt += column.ColumnName
Else
txt += delim + column.ColumnName
End If
n += 1
Next
End If
txt += vbCrLf
n = 0
For Each row As DataRow In dt.Rows
Dim line As String = ""
For Each column As DataColumn In dt.Columns
line += delim & row(column.ColumnName).ToString()
Next
If dt.Rows.Count - 1 = n Then
txt += line.Substring(1)
Else
txt += line.Substring(1) & vbCrLf
End If
n += 1
Next
Using sw As StreamWriter = New StreamWriter(fileloc)
sw.Write(txt)
End Using
dt.Dispose()
Return fileloc
End Function
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment