Reputation: 873
I have some SQL queries that I need to write out the results to a CSV file.
I'm currently storing the results in a DataSet.
What is the best way to to save each table (using a user-defined filename) as its own CSV file?
I'm using C#.
Upvotes: 3
Views: 24653
Reputation: 788
You can loop through the DataSet (Tables, Rows, Fields)
C# Example:
StringBuilder str = new StringBuilder();
foreach (DataTable dt in tempDataDS.Tables)
{
foreach (DataRow item in dt.Rows)
{
foreach (object field in item.ItemArray)
{
str.Append(field.ToString() + ",");
}
str.Replace(",", Environment.NewLine, str.Length - 1, 1);
}
}
try
{
File.AppendAllText("C:\\temp\\tempData.csv", str.ToString(), Encoding.UTF8);
}
catch (Exception ex)
{
Console.WriteLine("Error while writing content to csv file. \nException details: {0}", ex.ToString());
}
Upvotes: 2
Reputation: 529
You can convert a dataset to a CSV file as follows:
Code snippet:
StringBuilder str = new StringBuilder();
foreach (DataRow dr in this.NorthwindDataSet.Customers)
{
foreach (object field in dr.ItemArray)
{
str.Append(field.ToString + ",");
}
str.Replace(",", vbNewLine, str.Length - 1, 1);
}
try
{
My.Computer.FileSystem.WriteAllText("C:\\temp\\testcsv.csv", str.ToString, false);
}
catch (Exception ex)
{
MessageBox.Show("Write Error");
}
Hope this helps! Cheers!
Upvotes: 4
Reputation: 180917
SQL Server can export to csv on its own, have a look at
Edit: This solution isn't very tolerant of characters that need escaping in a csv, took a couple of minutes to write a breaking test. In other words, use with caution.
Upvotes: 0
Reputation: 7591
I use http://www.filehelpers.com anytime I need to export to CSV.
Upvotes: 1