Friday, March 20, 2009

Read Excel Database using ADO.Net

Excel is nothing but the other database only. It can be set like below
The table example as follows :
e.g. Student.xls
Here
-------------------------------------
Database ---------------Table
(Excel Workbook)------ (Excel Sheet)
-------------------------------------
Student.xls------------- personal_info
-------------------------------------
id ------- Name -------- Address
1 ------- Sachin -------- Patan
2 ------- Sam ---------- New Lands

Now below given code gives you access for the excel database.

C# code snippet

-----------------------------
using System;
using System.Data;
class Test{
public static void Main(){
IDbConnection con = new System.Data.Odbc.OdbcConnection("Driver={Microsoft Excel Driver (*.xls)};DBQ=db\\Student.xls");

// The above line is for connection string.
con.Open();
IDbCommand cmd = con.CreateCommand();
cmd.CommandText = "select id,name,address from [personal_info$]";

//Here the personal_info$ is the worksheet i.e. (table) of Student.xls Workbook i.e. (Database).
IDataReader reader = cmd.ExecuteReader();
while(reader.Read()){
Console.WriteLine("{0, -6}{1}{2}", reader.GetInt32(0), reader[1], reader["address"]);

// We can retrieve data with given three ways

// as reader.GetInt32(0) ----------> Gives first field.

// reader[1] ------------------------>Gives second field.

// reader["address"] --------------->Gives third field.
}
reader.Close();
con.Close();
}
}

No comments:

Post a Comment