Skip to content

Instantly share code, notes, and snippets.

@riyadparvez
Created January 6, 2013 14:48
Show Gist options
  • Save riyadparvez/4467668 to your computer and use it in GitHub Desktop.
Save riyadparvez/4467668 to your computer and use it in GitHub Desktop.
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
Copy link

Is GetDoubleQuotedString() a custom LINQ extension?

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