Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to save DataSet to a CSV file

Tags:

c#

sql

dataset

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#.

like image 746
user500741 Avatar asked Jan 20 '26 23:01

user500741


2 Answers

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!

like image 138
YashG99 Avatar answered Jan 22 '26 12:01

YashG99


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());
        }
like image 36
user797717 Avatar answered Jan 22 '26 12:01

user797717



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!