Sunday, June 28, 2009

Export Dataset to CSV File using VB.Net

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 comments:

  1. 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

    ReplyDelete
  2. Hi User,

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

    ReplyDelete
  3. 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

    ReplyDelete
  4. 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.

    ReplyDelete
  5. yes i got the same error :(

    ReplyDelete
  6. actually its Dim myString As New System.Text.StringBuilder() and mystring.append(",")

    ReplyDelete
  7. hi ,

    i'm getting an error in dr

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

    please help

    ReplyDelete
  8. This is the correct statement
    For Each dr In dt.Rows

    ReplyDelete