Write Dataset contents to a file as a csv?

G

Guest

I need to write the contents of a dataset to a comma delimited csv file that
includes the field names? Does anyone have a sample of how to do this?

Thanks
 
C

Cor Ligthert

Chris,

This is all I have the first part of the sample is creating a dataset and it
is without the names, however that is a questions of first one iterate
throught the columns and setting the columnnames in the first row..
\\\
Dim ds As New DataSet
Dim dt As New DataTable
ds.Tables.Add(dt)
For i As Integer = 0 To 99
Dim dc As New DataColumn(i.ToString)
dt.Columns.Add(dc)
Next
For i As Integer = 0 To 99
Dim dr As DataRow = dt.NewRow
For y As Integer = 0 To 99
dr(y) = i.ToString & y.tostring
Next
dt.Rows.Add(dr)
Next
'the routine

Dim sw As New IO.StreamWriter("C:\Bernie.csv")
For i As Integer = 0 To ds.Tables(0).Rows.Count - 1
Dim row As New System.Text.StringBuilder
row.Append("""")
For y As Integer = 0 To ds.Tables(0).Columns.Count - 1
row.Append(ds.Tables(0).Rows(i)(y).tostring)
If y <> ds.Tables(0).Columns.Count - 1 Then
row.Append(""",""")
' if you want it with a tab
' row.Append("""")
' row.Append(chr(09))
' row.Append("""")
Else
row.Append("""")
End If
Next
sw.WriteLine(row.ToString)
Next
sw.Flush()
sw.Close()
///

I hope this helps you something

Cor
 
S

Sahil Malik

You can write a datatable to a csv .. or a dataset to multiple csvs ... are
you asking for a sample to convert a datatable to a csv?

If so, that's easy and can be easily acheived using a loop similar to the
below.

int ColumnCount = dt.Columns.Count ;
foreach(DataRow in dt.Rows)
{
for (int i=0 ; i < ColumnCount ; i++)
{

}
}

- Sahil Malik
http://codebetter.com/blogs/sahil.malik/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top