Write a DataTable to CSV and read a DataTable from CSV

If you want to write a DataTable into a .csv file or fill a DataTable with a .csv file you can use the following method

public static string DataTableToCsv(DataTable table, char seperator)
StringBuilder data = new StringBuilder();

foreach (DataRow row in table.Rows)
foreach (object value in row.ItemArray)
data.Append(value.ToString() + seperator);

return data.ToString();

public static void DataTableToCsv(DataTable table, string path)
DataTableToCsv(table, path, ‘;’);

public static void DataTableToCsv(DataTable table, string path, char seperator)
using (StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.Default))
sw.Write(DataTableToCsv(table, seperator));

public static DataTable CsvToDataTable(string path, char seperator)
if (!File.Exists(path))
throw new FileNotFoundException();

DataTable table = new DataTable();

using (StreamReader reader = new StreamReader(path, Encoding.Default))
bool first = true;
while (!reader.EndOfStream)
string line = reader.ReadLine();
string[] cells = line.Split(seperator);

if (first)
first = false;
for (int i = 0; i < cells.Length; i++) { table.Columns.Add(); } } table.Rows.Add(); for (int i = 0; i < table.Columns.Count; i++) { table.Rows[table.Rows.Count - 1][i] = cells[i]; } } } return table; } public static DataTable CsvToDataTable(string path) { return CsvToDataTable(path, ';'); } [/sourcecode]

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: