Friday, August 22, 2014

NET : Create DataTable From CSV File

DataTable dt = new DataTable();
string line = String.Empty;
int i = 0;

using (StreamReader sr = File.OpenText(@path))
{
    while ((line = sr.ReadLine()) != null)
    {
        string[] data = line.Split(',');
        if (data.Length > 0)
        {
            if (i == 0)
            {
                int j = 0;
                foreach (var s in data)
                {
                    //create column
                    dt.Columns.Add(new DataColumn());
                    //add column name from first row
                    dt.Columns[j].ColumnName = data[j].ToString();
                    j++;
                }
                i++;
            }
            if (i > 1)
            {
                //if not first row (column name) then create data row
                DataRow row = dt.NewRow();
                row.ItemArray = data;
                dt.Rows.Add(row);
            }
            i++;
        }
    }
}
return dt;

No comments:

Post a Comment