Instantly share code, notes, and snippets.

Embed
What would you like to do?
DataTable to CSV extension methods. Export to CSV file, CSV string
public static class CSV
{
public static string ToCSV(this DataTable table)
{
var columnHeaders = (from DataColumn x in table.Columns
select x.ColumnName).ToArray();
StringBuilder builder = new StringBuilder(String.Join(",", columnHeaders));
builder.Append("\n");
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
builder.Append(row[i].ToString());
builder.Append((i == table.Columns.Count - 1) ? "\n" : ",");
}
}
return builder.ToString();
}
public static string ToExcelFormat(this DataTable table)
{
var columnHeaders = (from DataColumn x in table.Columns
select x.ColumnName).ToArray();
StringBuilder builder = new StringBuilder(String.Join(" ", columnHeaders));
builder.Append("\n");
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
builder.Append(row[i].ToString());
builder.Append(i == table.Columns.Count - 1 ? "\n" : " ");
}
}
return builder.ToString();
}
public static string ToDoubleQuotedCSV(this DataTable table)
{
var columnHeaders = (from DataColumn x in table.Columns
select x.ColumnName.GetDoubleQuotedString()).ToArray();
StringBuilder builder = new StringBuilder(String.Join(",", columnHeaders));
builder.Append("\n");
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
builder.Append(row[i].ToString().GetDoubleQuotedString());
builder.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
return builder.ToString();
}
public static void ToCSVFile(this DataTable table, string filePath)
{
if (File.Exists(filePath))
{
throw new ArgumentException();
}
string writeData = table.ToCSV();
writeData.WriteToFile(filePath);
}
public static void ToDoubleQuotedCSVFile(this DataTable table, string filePath)
{
if (File.Exists(filePath))
{
throw new ArgumentException();
}
string writeData = table.ToDoubleQuotedCSV();
writeData.WriteToFile(filePath);
}
public static string ToCSVRow(this IEnumerable<string> strings)
{
return String.Join(",", strings);
}
public static string ToDoubleQuotedCSVRow(this IEnumerable<string> strings)
{
var strs = strings
.Select(s => s.GetDoubleQuotedString())
.ToArray();
return String.Join(",", strs);
}
}
@dereckson

This comment has been minimized.

Copy link

dereckson commented Dec 1, 2013

Is GetDoubleQuotedString() a custom LINQ extension?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment