CSV to DataTable
Converting Microsoft Excel CSV to .Net DataTable:
After casually browsing the net for some good examples, everything I came across was too bulky or over-kill for what I needed this code for, so I decided to write my own.
The following code snippet is tested and works with .Net 2.0 or later. Please note “handleError()” method which is not defined in code below. This is simply generic static method accepting string and exception types to handle all exceptions in your application in a uniform manner.
The nice thing about this code compared to some other examples you may come across in your searches is that it works stand-alone without any external references or potentially buggy usage/constructors such as OleDB Jet provider.
It’s clean, concise, and to the point. Use it wisely. 😉
{
try {
bool HeaderColumnsAdded = false;
DataTable dt = new DataTable();
StreamReader reader = File.OpenText(FileNameWithPath);
string line = reader.ReadLine();
while ((line != null)) {
int colcounter = 0;
DataRow row = dt.NewRow();
foreach (string colvalue in line.Split(“,”)) {
if (HeaderColumnsAdded == false) {
dt.Columns.Add();
}
row(colcounter) = colvalue;
colcounter += 1;
}
HeaderColumnsAdded = true;
dt.Rows.Add(row);
line = reader.ReadLine();
}
reader.Close();
return dt;
}
catch (Exception ex0) {
handleError(ex0, “Ex0::MyCSVtoDT”);
throw new Exception(ex0.Message, ex0.InnerException);
return null;
}
}
Posted on March 2, 2010, in Programming & Development. Bookmark the permalink. 1 Comment.
Pingback: Import OData / XML / RSS / Webservice Feeds into Excel « Fraction of the Blogosphere