Created
March 17, 2020 08:58
-
-
Save imgen/35600172e870bd3be1b71c193ab3df44 to your computer and use it in GitHub Desktop.
Export DataTable to CSV File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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