Friday, September 11, 2009

Read Excel File using DataReader in ASP.Net using C#.Net


The following code is used to read the excel sheet using data reader in asp.net,
            using System.Data.Common;
      public void ReadXLSFile()
      {
        string Field1, Field2;
        Field1 = "";
        Field2 = "";
        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())
            {
                command.CommandText = "SELECT Field1, Field2 FROM [Sheet1$]";
                connection.Open();
                using (DbDataReader dr = command.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        Field1 = dr["Field1"].ToString();
                        Field2 = dr["Field2"].ToString();
                    }
                }
            }
        }
    }

No comments:

Post a Comment