Link to home
Start Free TrialLog in
Avatar of Bobby X
Bobby XFlag for United States of America

asked on

Reading Excel Spreadsheet using ADO.NET and DbDataReader

Hi,

Based on the code below, is there a way to get a total count of records that exist in the Excel worksheet (Cities)?

Thanks very much in advance!
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());
            }
        }
    }
}

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of tcs224694
tcs224694
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bobby X

ASKER

tcs224694,

Also, how do I dynamically get a row number for each record of the Excel?
Hi ,

Try this...

select (select SUM(1) from Cities) as 'Row Number', * from Cities;

Open in new window

Thanks for the grade and points