Posts Tagged ‘ csv ’

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);
}
data.AppendLine();
}

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]

Advertisements