While working as a .net programmer you may getting a requirement to convert a DataTable to CSV file format.
CSV - Comma Separated Value. Tabular format data are converted into comma separated values text file with the extension of csv. See sample below
Name, Age, Eid, Native
Raj, 27, E0025, Chennai
Kumar, 20, E0032, Nagercoil
Balu, 22, E0024, Mumbai
Raj, 25, E0026, Bangalore
To achieve this in C#
public void CreateCSVFile(DataTable dt, string strFilePath)
{
try
{
StreamWriter sw = new StreamWriter(strFilePath, false);
int columnCount = dt.Columns.Count;
for (int i = 0; i < columnCount ; i++)
{
sw.Write(dt.Columns[i]);
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < columnCount ; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
sw.Write(dr[i].ToString());
}
if (i < columnCount - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
catch (Exception ex)
{
throw ex;
}
}
Call the CreateCSVFile function like below by passing the DataTable to convert and the path of the CSV file to be saved.
static void Main(string[] args)
{
CreateCSVFile(dt,"D://ConvertedFile.csv");
}