I'm going to explain how extract data from CSV file using c#. First you have to declare two string variables and their properties for store directory and filename of CSV file which you want to extract data.
private string dirCSV;
private string fileNevCSV;
public string FileNevCSV
{
get { return fileNevCSV; }
set { fileNevCSV = value; }
}
public string dirCSV
{
get { return dirCSV; }
set { dirCSV = value; }
}
In the second step connect to the data source and fill it to the dataset.
public DataSet loadCVS(int noofrows)
{
DataSet ds = new DataSet();
try
{
// Creates and opens an ODBC connection
string strConnString = "Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq=" + this.dirCSV.Trim() +";Extensions=asc,csv,tab,txt;Persist Security Info=False";
string sql_select;
OdbcConnection conn;
conn = new OdbcConnection(strConnString.Trim());
conn.Open();
//Creates the select command text
if (noofrows == -1)
{
sql_select = "select * from [" + this.FileNevCSV.Trim() + "]";
}
else
{
sql_select = "select top " + noofrows + " * from [" + this.FileNevCSV.Trim() + "]";
}
//Creates the data adapter
OdbcDataAdapter obj_oledb_da = new OdbcDataAdapter(sql_select, conn);
//Fills dataset with the records from CSV file
obj_oledb_da.Fill(ds, "csv");
//closes the connection
conn.Close();
}
catch (Exception e) //Error
{
}
return ds;
}
In the third step extract data to DataTable from generated DataSet.
this.dirCSV = "file path";
this.fileNevCSV ="file name";
DataSet ds = loadCVS(-1);
DataTable table = ds.Tables[0];
foreach (DataRow row in table.Rows)
{
//iterate through the DataTable.
}
Thanks.
Happy coding...
kaka KakaPosted Mar 24, 2014, 3:34 AM
can u pls give me a full project of this code, i'm new bie with c# plsss...
Tej MauryaPosted Jun 21, 2013, 2:42 AM
IT is working but I have a problem if there is a cell with comma it is taking it AS NULL. hOW TO GET that value instead of null
ThomasPosted Jul 14, 2011, 2:46 PM
I'm not sure when this was written or if you've gotten this notice before but I have code similar to this (using JET instead of ODBC) and have run into a serious drawback. I have a field that is numbers, but I use a CSV format instead of Excel because I NEED to keep the leading zeros. when I use this method it reads that field as a double and drops the leading zeros.
Girish SarbhukanPosted Jan 25, 2011, 1:51 AM
b bn