Sunday, November 9, 2008

Reading and Writing Excel Spreadsheets Using ADO.NET C# DbProviderFactory

This is a good post talking about reading excel spreadsheets using ADO.net. You can read the data using SQL statement easily.

Read Excel Spreadsheet using ADO.NET and DbDataReader
Once you have the connection string all normal ADO.NET coding applies. Here is some sample code that reads each row of the excel worksheet using DbDataReader. You don't have to use the DbProviderFactory Classes. I thought I would show it just for kicks.
string connectionString = @"Provider=Microsoft.Jet. OLEDB.4.0;Data Source=Book1.xls;Extended Properties=""Excel 8.0;HDR=YES;""";
DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.OleDb");
using (DbConnection connection = factory.CreateConnection())
{
connection.ConnectionString = connectionString;
using (DbCommand command = connection.CreateCommand())
{
// Cities$ comes from the name of the worksheet
command.CommandText = "SELECT ID,City,State FROM [Cities$]";
connection.Open();
using (DbDataReader dr = command.ExecuteReader())
{
while (dr.Read())
{
Debug.WriteLine(dr["ID"].ToString());
}
}
}
}


Reference:
http://davidhayden.com/blog/dave/archive/2006/05/26/2973.aspx

David Hayden's blog is a great blog that regularly posts ASP.net Data Access article.

No comments: