Skip to content

Instantly share code, notes, and snippets.

@imgen
Created March 17, 2020 08:58
Show Gist options
  • Save imgen/35600172e870bd3be1b71c193ab3df44 to your computer and use it in GitHub Desktop.
Save imgen/35600172e870bd3be1b71c193ab3df44 to your computer and use it in GitHub Desktop.
Export DataTable to CSV File
public static void ToCSV(this DataTable dtDataTable, string strFilePath)
{
StreamWriter sw = new StreamWriter(strFilePath, false);
//headers
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
sw.Write(dtDataTable.Columns[i]);
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
foreach (DataRow dr in dtDataTable.Rows)
{
for (int i = 0; i < dtDataTable.Columns.Count; i++)
{
if (!Convert.IsDBNull(dr[i]))
{
string value = dr[i].ToString();
if (value.Contains(','))
{
value = String.Format("\"{0}\"", value);
sw.Write(value);
}
else
{
sw.Write(dr[i].ToString());
}
}
if (i < dtDataTable.Columns.Count - 1)
{
sw.Write(",");
}
}
sw.Write(sw.NewLine);
}
sw.Close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment