C#.Net upload Datas from CSV file into DataTable

August 31, 2011 | Posted by: admin | C#, Programming language | 1 Comment

You can not read the CSV file using the Split() function because the CSV itself comma separated value. If you have a CSV file from which you want to upload the data use below given code. First it reads the data from CSV file into C# Data Table. Form the data table you can load the data into database.

Method


public static DataTable CsvToDataTable(string file, bool isRowOneHeader)
{
DataTable dt = new DataTable();

//String[] csvData = File.ReadAllLines(HttpContext.Current.Server.MapPath(file));

String[] csvData = File.ReadAllLines(file);

//if no data in the file it will throw an exception
if (csvData.Length == 0)
{
throw new Exception(Constant.C_H_NO_data_available);
}

String[] headings = csvData[0].Split(',');
int index = 0; //will be zero or one depending on isRowOneHeader

if (isRowOneHeader) //if first record lists headers
{
index = 1; //so we won't take headings as data

//for each heading
for (int i = 0; i < headings.Length; i++)
{
//replace spaces with underscores for column names
headings[i] = headings[i].Replace(" ", "_");

//add a column for each heading
dt.Columns.Add(headings[i], typeof(string));
}
}
else //if no headers just go for col1, col2 etc.
{
for (int i = 0; i < headings.Length; i++)
{
//create arbitary column names
dt.Columns.Add("col" + (i + 1).ToString(), typeof(string));
}
}

//populate the DataTable
for (int i = index; i < csvData.Length; i++)
{
//create new rows
DataRow row = dt.NewRow();

for (int j = 0; j < headings.Length; j++)
{
//fill them
row[j] = csvData[i].Split(',')[j];
}

//add rows to over DataTable
dt.Rows.Add(row);
}

//return the CSV DataTable
return dt;
}

How to call the above method

CsvToDataTable(csvfilepath, false);

The second parameter is for header, if you csv file contain header in the first row use "true" else "false"

Comments (1)

 

  1. [...] the data use below given code. First it reads the data from CSV file … Read the original: C#.Net upload Datas from CSV file into DataTable | Gopi's Digital … Posted in Uncategorized Tags: up-load, upload a file « Pirate Bay founders launch legal [...]

Leave a Reply