-
-
Save A1iAshoor/fb954d0dabe0250edf0dbb6b7484de4a to your computer and use it in GitHub Desktop.
DataTable to CSV extension methods. Export to CSV file, CSV string
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
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment