Created
June 14, 2010 16:23
-
-
Save SamWM/437902 to your computer and use it in GitHub Desktop.
Extension Methods for Generating CSV strings from objects (C# 3.0)
This file contains hidden or 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
| using System; | |
| public static class CSVExtensions | |
| { | |
| public static string ToCSV(this DataTable dt) | |
| { | |
| string output = string.Empty; | |
| string tmp; | |
| char[] special = new char[] { '"', '\n', '\r', ',' }; | |
| // loop through all columns | |
| for (int i = 0; i < dt.Columns.Count; i++) | |
| { | |
| output += "\"" + dt.Columns[i].ColumnName + "\""; | |
| // if last column, add \r\n, otherwise , | |
| output += (dt.Columns.Count == (i + 1)) ? "\r\n" : ","; | |
| } | |
| foreach (DataRow dr in dt.Rows) | |
| { | |
| for (int i = 0; i < dt.Columns.Count; i++) | |
| { | |
| tmp = dr[i].ToString(); | |
| // if there are any special characters, wrap in " | |
| if (tmp.IndexOfAny(special) > 0) | |
| { | |
| // replace " with "" | |
| // replace \r\n or \r with \n | |
| tmp = tmp.Replace("\"", "\"\"").Replace("\r\n", "\n").Replace('\r', '\n'); | |
| tmp = "\"" + tmp + "\""; | |
| } | |
| output += tmp; | |
| // if last column, add \r\n, otherwise , | |
| output += (dt.Columns.Count == (i + 1)) ? "\r\n" : ","; | |
| } | |
| } | |
| return output; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment