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
throwing error at dt in
ReplyDeleteFor 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
Hi User,
ReplyDeleteThe above code is tested only in VB.net, anyway i ll test for ASP.net in future and post here..
Hey User
ReplyDeleteThe error was due to .rows missing in the following line
For Each dr In dt.Rows
I am changing the code accordingly..
Thank u
I am new in coding and i m getting error:
ReplyDeletemyString.AppendText is giving error of "AppendText" is not a memeber of String. can u please give me reply as soon as possible.
yes i got the same error :(
ReplyDeleteactually its Dim myString As New System.Text.StringBuilder() and mystring.append(",")
ReplyDeletehi ,
ReplyDeletei'm getting an error in dr
Variable 'dr' hides a variable in an enclosing block.
please help
This is the correct statement
ReplyDeleteFor Each dr In dt.Rows