Free Information Technology Magazines and eBooks

Thursday, August 05, 2010

C# CSV Writer: Class To Extract Data To CSV File

C# CSV Writer: Class To Extract Data To CSV FileComma Separated Values or CSV is one of the commonly used data exchange format between programs. You can learn how to read CSV by reading the following articles; Read CSV to Array and Read CSV using LINQ. In this post, I will show you how you can write a records from a database in to CSV file. The class wrapper I used here is not originally created by me but was downloaded from the internet. The class has two main functions: one writes and return the data as string, and the second function writes data to text stream. The example I will show you will connect to a database, open records with SqlDataReader class, convert it to DataTable and then write it into a CSV file. Here is the step-by-step procedure.


1. Download the CSV writer class and add it to your project.
2. Include the following namespaces in your Using directive.


using System.Data.SqlClient;
using System.IO;


3. Connect to the database using SqlConnection, download the data using SqlCommand and SqlDataReader, and call CSVWriter.WriteToStream to write the data to CSV file as shown below:


SqlConnection con = new SqlConnection();
SqlCommand cmd = new SqlCommand();
try
{
con.ConnectionString = Settings.Default.ConnectionString;
con.Open();
cmd.Connection = con;
cmd.CommandText = "SELECT * FROM vwCSVData WHERE DepositDate>='" + dtSearchFrom.Value.Date.ToShortDateString() + "' AND DepositDate<='" + dtSearchTo.Value.Date.ToShortDateString() + "'";
SqlDataReader lrd = cmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable dt = new DataTable();
dt.Load(lrd); //convert sqlreader records to a datatable
FileInfo f = new FileInfo(DateTime.Now.ToString("M-d hmmyy") + ".csv");
StreamWriter writeFile = f.CreateText();
CSVWriter.WriteToStream(writeFile, dt, false, false); //call the CSVWriter class to write the data into CSV
writeFile.Close();
MessageBox.Show("Data was successfully extracted to " + f.FullName + "!", "Extract Data");

}
catch (Exception ex)
{
MessageBox.Show("Error while extracting check records. " + ex.Message, "Extract Records");
}
finally
{
con.Close();
}

4. Hit F5 to test your project.

To stay up-to-date on Coding Tips & Tricks, subscribe now.

1 comments:

Anonymous said...

thanks.