Internal Use Only▲
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 [Link] gets created automatically in the folder where all your CSV files reside.
But if you use connection string, you have to create [Link] file on your own. We are
going to see the latter approach.
All rights reserved. No spreading without permission of ZTE. Page1
Internal Use Only▲
[Link] File (Text File Driver)
When the Text driver is used, the format of the text file is determined by using a schema
information file. The schema information file, which is always named [Link] and
always kept in the same directory as the text data source, provides the IISAM with
information about the general format of the file, the column name and data type
information, and a number of other data characteristics.
Using the demo application
For successfully running the application you need [Link] file and a database with a table
having three columns. But all this is provided in the demo application. So you need not
worry. Follow these steps to run the demo application:
1. First run [Link] application.
2. The screen shown below will appear.
3. Fill the required details and click the button "Install".
4. Make sure that a folder named "Test" is created in "D:" drive with the [Link] file in it.
5. Now run our main application i.e. [Link].
6. Keep the default folder and file path as it is.
7. First click "Import CSV data" to import the CSV data.
8. Now click "Save", to save the data in the database.
Using the source code
Some important parts of the code are discussed below
All rights reserved. No spreading without permission of ZTE. Page2
Internal Use Only▲
Create [Link]
This is a function writeSchema(). It creates the [Link] file dynamically.
Hide Shrink Copy Code
/*[Link] File (Text File Driver)
When the Text driver is used, the format of the
text file is determined by using a schema information
file. The schema information file, which is always named
[Link] and always kept in the same directory as the
text data source, provides the IISAM with information
about the general format of the file, the column name
and data type information, and a number of other data
characteristics*/
private void writeSchema()
{
try
{
FileStream fsOutput =
new FileStream ([Link]+"\\[Link]",
[Link], [Link]);
StreamWriter srOutput = new StreamWriter (fsOutput);
string s1, s2, s3,s4,s5;
s1="["+strCSVFile+"]";
s2="ColNameHeader="+[Link] ();
s3="Format="+strFormat;
s4="MaxScanRows=25";
s5="CharacterSet=OEM";
[Link]([Link]()+'\n'+[Link]()+
'\n'+[Link]()+'\n'+
[Link]()+'\n'+[Link]());
[Link] ();
[Link] ();
}
catch (Exception ex)
{
[Link]([Link]);
}
finally
{
}
All rights reserved. No spreading without permission of ZTE. Page3
Internal Use Only▲
Function for importing the CSV Data
This function ConnectCSV (string filetable) takes the .csv file name as argument
and returns the dataset containing the imported data.
Hide Shrink Copy Code
public DataSet ConnectCSV (string filetable)
{
DataSet ds = new DataSet ();
try
{
/* You can get connected to driver either by using
DSN or connection string. Create a connection string
as below, if you want to use DSN less connection.
The DBQ attribute sets the path of directory which
contains CSV files*/
string strConnString=
"Driver={Microsoft Text Driver (*.txt;*.csv)};
Dbq="+[Link]()+";
Extensions=asc,csv,tab,txt;
Persist Security Info=False";
string sql_select;
[Link] conn;
//Create connection to CSV file
conn = new [Link](
[Link] ());
// For creating a connection using DSN, use following line
//conn = new [Link](DSN="MyDSN");
//Open the connection
[Link] ();
//Fetch records from CSV
sql_select="select * from ["+ filetable +"]";
obj_oledb_da=new [Link](
sql_select,conn);
//Fill dataset with the records from CSV file
obj_oledb_da.Fill(ds,"Stocks");
All rights reserved. No spreading without permission of ZTE. Page4
Internal Use Only▲
//Set the datagrid properties
[Link]=ds;
[Link]="Stocks";
//Close Connection to CSV file
[Link] ();
}
catch (Exception e) //Error
{
[Link] ([Link]);
}
return ds;
}
Code for inserting the data
This is a code written in the button's click event btnUpload_Click. This actually inserts
the data in the database.
Hide Shrink Copy Code
private void btnUpload_Click(object sender,
[Link] e)
{
try
{
// Create an SQL Connection
// You can use actual connection
// string instead of ReadConFile()
SqlConnection con1=
new SqlConnection(ReadConFile().Trim());
SqlCommand cmd = new SqlCommand();
SqlCommand cmd1 = new SqlCommand();
// Create Dataset
DataSet da = new DataSet();
/* To actually fill the dataset,
Call the function ImportCSV and assign
the returned dataset to new dataset as below */
da=[Link](strCSVFile);
All rights reserved. No spreading without permission of ZTE. Page5
Internal Use Only▲
/* Now we will collect data from data table
and insert it into database one by one.
Initially there will be no data in database
so we will insert data in first two columns
and after that we will update data in same row
for remaining columns. The logic is simple.
'i' represents rows while 'j' represents columns*/
[Link]=con1;
[Link]=[Link];
[Link]=con1;
[Link]=[Link];
[Link]();
for(int i=0;i<=[Link]["Stocks"].[Link]-1;i++)
{
for(int j=1;j<=[Link]["Stocks"].[Link]-1;j++)
{
[Link]=
"Insert into Test(srno,
"+[Link]["Stocks"].Columns[0].[Link]()+")
values("+(i+1)+",
'"+[Link]["Stocks"].Rows[i].[Link](0)+"')";
/* For UPDATE statement, in where clause you
need some unique row identifier. We are using
‘srno’ in WHERE clause. */
[Link]=
"Update Test set "
+[Link]["Stocks"].Columns[j].[Link]()+"
= '"+[Link]["Stocks"].Rows[i].[Link](j)+
"' where srno ="+(i+1);
[Link]();
[Link]();
}
}
[Link]();
}
catch(Exception ex)
{
[Link]([Link]);
}
finally
All rights reserved. No spreading without permission of ZTE. Page6
Internal Use Only▲
{
[Link]=false;
}
}
All rights reserved. No spreading without permission of ZTE. Page7