Export Dataset to CSV File using VB.Net

Posted by VIJI Sunday, June 28, 2009

The following VB.Net Code Snippet is used to export Dataset to csv File.

All Data tables of a data set will be exported to CSV File.



Private Sub ExportDatasetToCsv(ByVal MyDataSet As DataSet)

'Declaration of Variables


Dim dt As DataTable
Dim dr As DataRow

Dim myString As String
Dim bFirstRecord As Boolean = True

Dim myWriter As New System.IO.StreamWriter("C:\MyTestCSV.csv")


myString = ""

Try

      For Each dt In MyDataSet.Tables

             For Each dr As DataRow In dt.rows

            bFirstRecord = True

                  For Each field As Object In dr.ItemArray

                       If Not bFirstRecord Then

                       myString.AppendText(",")


                        End If

                      myString.AppendText(field.ToString)

                     bFirstRecord = False

                  Next

                    'New Line to differentiate next row
                    myString.AppendText(Environment.NewLine)

          Next

Next

Catch ex As Exception

      MsgBox (ex.Message)


End Try


End Sub

'Write the String to the Csv File

myWriter.WriteLine(myString)

'Clean up
myWriter.Close()


End Sub





USAGE

ExportDatasetToCsv (ds)


Where ds is the dataset.


It will export all data tables of data set to csv File C:\MyTestCSV.csv

8 Responses to Export Dataset to CSV File using VB.Net

  1. Anonymous Says:
  2. throwing error at dt in
    For Each dr As DataRow In dt .. statement

    saying that.. "Expression is of type System.Data.DataTable, which is not a collection type" in ASP.Net 3.5

     
  3. Hi User,

    The above code is tested only in VB.net, anyway i ll test for ASP.net in future and post here..

     
  4. Hey User

    The error was due to .rows missing in the following line

    For Each dr In dt.Rows

    I am changing the code accordingly..

    Thank u

     
  5. Anonymous Says:
  6. I am new in coding and i m getting error:
    myString.AppendText is giving error of "AppendText" is not a memeber of String. can u please give me reply as soon as possible.

     
  7. Anonymous Says:
  8. yes i got the same error :(

     
  9. tanay thapa Says:
  10. actually its Dim myString As New System.Text.StringBuilder() and mystring.append(",")

     
  11. ammu Says:
  12. hi ,

    i'm getting an error in dr

    Variable 'dr' hides a variable in an enclosing block.

    please help

     
  13. Anonymous Says:
  14. This is the correct statement
    For Each dr In dt.Rows

     

Post a Comment