Yama,
Here's a quick VB.NET 1.1 export routine that is very general (too
general?):
Its based on a DataSet, however you should be able to adopt it to a
DataReader instead.
' Required imports
Imports System.IO ' for the StreamWriter
Imports System.Text ' for the UnicodeEncoding
' sample usage
Export("Customers.csv", DataSet1.Tables("Customers"))
Export("Employees.csv", DataSet1.Tables("Employees"))
Public Sub Export(ByVal path As String, ByVal table As DataTable)
Dim output As New StreamWriter(path, False, UnicodeEncoding.Default)
Dim delim As String
' Write out the header row
delim = ""
For Each col As DataColumn In table.Columns
output.Write(delim)
output.Write(col.ColumnName)
delim = ","
Next
output.WriteLine()
' write out each data row
For Each row As DataRow In table.Rows
delim = ""
For Each value As Object In row.ItemArray
output.Write(delim)
If TypeOf value Is String Then
output.Write(""""c) ' thats four double quotes and a c
output.Write(value)
output.Write(""""c) ' thats four double quotes and a c
Else
output.Write(value)
End If
delim = ","
Next
output.WriteLine()
Next
output.Close()
End Sub
You can change (or remove) the Encoding parameter above to suit your needs,
I used Unicode as the table had non ASCII characters in it. Also when
writing strings, I don't deal with double quotes in the string. If you make
the StreamWriter a parameter it will be much more flexible (you could go to
a memory stream to support cut & paste). I use the default formatting for
numeric types.
You can change it to use a DataView (for sorting & filtering for example) by
changing the following lines:
'Public Sub Export(ByVal path As String, ByVal table As DataTable)
Public Sub Export(ByVal path As String, ByVal view As DataView)
'For Each col As DataColumn In table.Columns
For Each col As DataColumn In view.Table.Columns
'For Each row As DataRow In table.Rows
For Each row As DataRowView In view
'For Each value As Object In row.ItemArray
For Each value As Object In row.Row.ItemArray
Hope this helps
Jay