public static class Extensions
{
private const string CSV_SEPARATOR = ",";
private const string QUOTE = "\"";
private const string ESCAPED_QUOTE = "\"\"";
private static char[] CHARACTERS_THAT_MUST_BE_QUOTED = { ',', '"', '\n' };
public static string ToCSV(this DataTable table, List<String> columnsExcluded, bool includeSeparatorSpecificationOnFirstRow)
{
var result
= new StringBuilder
();
// Aggiunta riga di specifica del separatore per excel
if (includeSeparatorSpecificationOnFirstRow)
{
result.Append(string.Concat("sep=", CSV_SEPARATOR));
result.Append(Environment.NewLine);
}
var columnsIncluded = table.Columns.Cast<DataColumn>().ToArray();// table.Columns.Cast<DataColumn>().Where(col => columnsExcluded.Contains(col.ColumnName) == false).ToArray();
var columnsIncluded2 = table.Columns.Cast<DataColumn>().Where(col => columnsExcluded.Contains(col.ColumnName) == false).ToArray();
for (int i = 0; i < columnsIncluded.Length; i++)
{
string toAdd = columnsIncluded[i].ColumnName;
string toAddEscaped = Escape(toAdd);
result.Append(toAddEscaped);
result.Append(i == columnsIncluded.Length - 1 ? Environment.NewLine : CSV_SEPARATOR);
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < columnsIncluded.Length; i++)
{
string toAdd = row[columnsIncluded[i].ColumnName].ToString();
string toAddEscaped = Escape(toAdd);
result.Append(toAddEscaped);
result.Append(i == columnsIncluded.Length - 1 ? Environment.NewLine : CSV_SEPARATOR);
}
}
return result.ToString();
}
private static string Escape(string s)
{
if (s.Contains(QUOTE))
s = s.Replace(QUOTE, ESCAPED_QUOTE);
if (s.IndexOfAny(CHARACTERS_THAT_MUST_BE_QUOTED) > -1)
s = QUOTE + s + QUOTE;
return s;
}
//private static string Unescape(string s)
//{
// if (s.StartsWith(QUOTE) && s.EndsWith(QUOTE))
// {
// s = s.Substring(1, s.Length - 2);
// if (s.Contains(ESCAPED_QUOTE))
// s = s.Replace(ESCAPED_QUOTE, QUOTE);
// }
// return s;
//}
}