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:
thanks.
Post a Comment