.NET DataTable to CSV

By Mash B

You just need to call below function with datatable and path parameter

public void DataTableTOCSV(DataTable dt , string path)
{
       using(StreamWriter writer = new StreamWriter(path))
       {
       String[] colArray = new String[dt.Columns.Count];

       //Extract column names in array
       for (int i = 0; i < dt.Columns.Count-1; i++)
       {
         colArray.SetValue(dt.Columns[i].ColumnName, i);
       }

       //Write Header
       writer.WriteLine(string.Join(",", colArray));

       foreach (DataRow item in dt.Rows)
       {
         writer.WriteLine(string.Join(",",(string[])item.ItemArray));
       }
     }
}

.NET DataTable to CSV  (1076 Views)