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:
Post a Comment