IntroductionMost of the time .NET developer asking question in message board, how to export data from DataTable to CSV or other file format.Hence i would try to give code snippet to Export data from DataTable to CSV. Code Snippet public void CreateCSVFile(DataTable dt, string strFilePath)
{
try
{
// Create the CSV file to which grid data will be exported.
StreamWriter sw = new StreamWriter(strFilePath, false);
int iColCount = dt.Columns.Count;
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < iColCount-2; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < iColCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
Note: Pass the DATATABLE and FILEPATH + FILENAME to the above function.I used here strFilePath = FILEPATH + FILENAME. that's all, Enjoy the simple code snippets. Thank you
|