Exporting a DataTable to a CSV file
Hi
I was hoping their was a way I can use the ADO.net functionality to write the data contained in a DataTable object to a CSV file.
Iām quite new to C# development so I need a kick in the right direction.
Thanks
[814 byte] By [
tinny4u] at [2007-12-18]
Have you tried the stream writer:
StreamWriter sw = new StreamWriter(@"C:\TestFile.Txt");
foreach (DataRow dr in dt.Rows)
{
sw.WriteLine("{0},{1},{2},{3}", dr[0], dr[1],dr[2].dr[3]);
}
sw.Close();
*****************************************************************************
PS I'm a beginner
Yep, thats basically what im doing in the mean time.
Im looking for away that i can get ADO.net to do it for me, in a similar way that you can use ADO to write out XML.
Its all to do with your connection string.
With accessing CSV you need to thing of a folder as a non-relational database and the csv files in the folder as tables. Once you think like that you can understand how SQL statements with CSV files work. Here's a console application that demonstrates how to export CSV data.
Imports
System.Data.OleDbImports
System.IO
Module
Module1Sub Main()TryDim conn As New OleDbConnectionconn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=C:\CSVFiles;Extended Properties=Text;"
conn.Open()
Dim cmd As New OleDbCommandcmd.Connection = conn
cmd.CommandText = "CREATE TABLE afile.csv (Col1 string, Col2 string);"
cmd.ExecuteNonQuery()
cmd.CommandText = "INSERT INTO aFile.csv ([Col1], [Col2]) VALUES ('Hello', 'World');"
cmd.ExecuteNonQuery()
conn.Close()
Catch ex As ExceptionConsole.WriteLine(ex.Message)
End TryConsole.WriteLine("Complete. Press any key to exit.")
Console.ReadLine()
End SubEnd
Module