Tuesday, September 22, 2009

Read CSV File and covert to DataTable

public static DataTable ReadCSV(string filePath, DataTable csvTable)

{

//DataTable csvTable = new DataTable();

// open the file "data.csv" which is a CSV file with headers

using (CsvReader csv = new CsvReader(new StreamReader(filePath), true))

{

// missing fields will not throw an exception,

// but will instead be treated as if there was a null value

csv.MissingFieldAction = MissingFieldAction.ReplaceByNull;

// to replace by "" instead, then use the following action:

//csv.MissingFieldAction = MissingFieldAction.ReplaceByEmpty;

int fieldCount = csvTable.Columns.Count;

// this bit could be modified to fine-tune the columns

while (csv.ReadNextRecord())

{

DataRow newRow = csvTable.NewRow();

for (int i = 0; i < fieldCount; i++)

newRow[i] = csv[i] == null ? "MISSING" : csv[i];

csvTable.Rows.Add(newRow);

}

}

return csvTable;

}

No comments: