Created
November 25, 2015 14:31
-
-
Save tonyjoanes/71220cff3a16864eec72 to your computer and use it in GitHub Desktop.
Convert a generic list to CSV
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
private static string CreateCsvTextFile<T>(List<T> data) | |
{ | |
var properties = typeof(T).GetProperties(); | |
var result = new StringBuilder(); | |
var headings = properties.Select(x => x.Name.ToString()); | |
var headerLine = string.Join(",", headings); | |
result.AppendLine(headerLine); | |
foreach (var row in data) | |
{ | |
var values = properties.Select(p => p.GetValue(row, null)) | |
.Select(v => StringToCsvCell(Convert.ToString(v))); | |
var line = string.Join(",", values); | |
result.AppendLine(line); | |
} | |
return result.ToString(); | |
} | |
private static string StringToCsvCell(string str) | |
{ | |
bool mustQuote = (str.Contains(",") || str.Contains("\"") || str.Contains("\r") || str.Contains("\n")); | |
if (mustQuote) | |
{ | |
StringBuilder sb = new StringBuilder(); | |
sb.Append("\""); | |
foreach (char nextChar in str) | |
{ | |
sb.Append(nextChar); | |
if (nextChar == '"') | |
sb.Append("\""); | |
} | |
sb.Append("\""); | |
return sb.ToString(); | |
} | |
return str; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment