devxlogo

DataTable2CSV – Saving a DataTable to a CSV file

DataTable2CSV – Saving a DataTable to a CSV file

' Save the input DataTable to a CSV file. By default the values are Tab ' delimited, but you can use the second overload version to use any other ' string you want.'' Example:'    Dim ds As New DataSet'    SqlDataAdapter1.Fill(ds, "Users")'    DataTable2CSV(ds.Tables("Users"), "D:Users.txt")Sub DataTable2CSV(ByVal table As DataTable, ByVal filename As String)    DataTable2CSV(table, filename, vbTab)End SubSub DataTable2CSV(ByVal table As DataTable, ByVal filename As String, _    ByVal sepChar As String)    Dim writer As System.IO.StreamWriter    Try        writer = New System.IO.StreamWriter(filename)        ' first write a line with the columns name        Dim sep As String = ""        Dim builder As New System.Text.StringBuilder        For Each col As DataColumn In table.Columns            builder.Append(sep).Append(col.ColumnName)            sep = sepChar        Next        writer.WriteLine(builder.ToString())        ' then write all the rows        For Each row As DataRow In table.Rows            sep = ""            builder = New System.Text.StringBuilder            For Each col As DataColumn In table.Columns                builder.Append(sep).Append(row(col.ColumnName))                sep = sepChar            Next            writer.WriteLine(builder.ToString())        Next    Finally        If Not writer Is Nothing Then writer.Close()    End TryEnd Sub

See also  How IoT Tech Will Transform Logistics
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist