Internal Use Only : All Rights Reserved. No Spreading Without Permission of ZTE
Internal Use Only : All Rights Reserved. No Spreading Without Permission of ZTE
Introduction
Nowadays it is common in applications to have the functionality of reading the CSV data.
My current project needed one. Even after searching for long, I could not get one which
could satisfy my requirements. But after doing considerable amount of study, I came up
with the following tool. CSV files stand for Comma Separated Value files. They are
common text files with comma delimited values. Though the default delimiter is comma
(,), we can specify other characters as delimiters like the semi-colon (;), colon (:), asterisk
(*). But you cannot specify double quotes (") as a delimiter. I have used Microsoft Text
Drivers for reading the CSV data. You have to use ODBC connection for accessing the
CSV data. You can either create a DSN or use the connection string. If you create a DSN,
the schema.inifile gets created automatically in the folder where all your CSV files reside.
But if you use connection string, you have to create schema.ini file on your own. We are
going to see the latter approach.
Create schema.ini
This function ConnectCSV (string filetable) takes the .csv file name as argument
and returns the dataset containing the imported data.
string strConnString=
"Driver={Microsoft Text Driver (*.txt;*.csv)};
Dbq="+txtCSVFolderPath.Text.Trim()+";
Extensions=asc,csv,tab,txt;
Persist Security Info=False";
string sql_select;
System.Data.Odbc.OdbcConnection conn;
obj_oledb_da=new System.Data.Odbc.OdbcDataAdapter(
sql_select,conn);
//Fill dataset with the records from CSV file
obj_oledb_da.Fill(ds,"Stocks");
dGridCSVdata.DataSource=ds;
dGridCSVdata.DataMember="Stocks";
//Close Connection to CSV file
conn.Close ();
}
catch (Exception e) //Error
{
MessageBox.Show (e.Message);
}
return ds;
}
This is a code written in the button's click event btnUpload_Click. This actually inserts
the data in the database.
SqlConnection con1=
new SqlConnection(ReadConFile().Trim());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd1 = new SqlCommand();
// Create Dataset
DataSet da = new DataSet();
da=this.ConnectCSV(strCSVFile);
cmd.Connection=con1;
cmd.CommandType=CommandType.Text;
cmd1.Connection=con1;
cmd1.CommandType=CommandType.Text;
con1.Open();
for(int i=0;i<=da.Tables["Stocks"].Rows.Count-1;i++)
{
for(int j=1;j<=da.Tables["Stocks"].Columns.Count-1;j++)
{
cmd.CommandText=
"Insert into Test(srno,
"+da.Tables["Stocks"].Columns[0].ColumnName.Trim()+")
values("+(i+1)+",
'"+da.Tables["Stocks"].Rows[i].ItemArray.GetValue(0)+"')";
cmd1.CommandText=
"Update Test set "
+da.Tables["Stocks"].Columns[j].ColumnName.Trim()+"
= '"+da.Tables["Stocks"].Rows[i].ItemArray.GetValue(j)+
"' where srno ="+(i+1);
cmd.ExecuteNonQuery();
cmd1.ExecuteNonQuery();
}
}
con1.Close();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
btnUpload.Enabled=false;
}
}