Question Export to .CSV

chrisguk

Active member
Joined
Nov 20, 2011
Messages
29
Programming Experience
Beginner
I have been searching the net and these forums for a couple of days to find a solution that will allow me to export my data to .csv


Are there any resources around for this function?
 
You would simply use a StreamWriter to write the data to the file. Most likely you would use two nested loops to traverse your data by row and by column but, as you haven't told us anything about your data, that is just a guess. This code would write the contents of a DataTable to a CSV file:
Using writer As New StreamWriter(filePath)
    For rowIndex = 0 To table.Rows.Count - 1
        Dim row = table.Rows(rowIndex)

        If rowIndex > 0 Then
            'Add a line break before all but the first line.
            writer.WriteLine()
        End If

        For columnIndex = 0 To table.Columns.Count - 1
            If columnIndex > 0 Then
                'Add a comma before all but the first field.
                writer.Write(",")
            End If

            'Write out the data for the current field.
            writer.Write(row(columnIndex))
        Next
    Next
End Using
 
A simplification can be done in .Net 4 if you don't need special handling for each cell value. A String.Join overload has been added for Object arrays for implicit String conversion of each value, Join Method (String, Object[])
This enables you to do a For-Each loop of rows and String.Join the ItemArray:
Using writer As New IO.StreamWriter(filePath)
    For Each row As DataRow In table.Rows
        writer.WriteLine(String.Join(",", row.ItemArray))
    Next
End Using
 
Back
Top