Reading values from an Excel File

后端 未结 5 1572
無奈伤痛
無奈伤痛 2021-01-19 03:09

I want to get a value from 12 excel sheet. is there any way that i get the values without opening the excel sheet? I am using vb.net. Please post an example code, if there i

5条回答
  •  心在旅途
    2021-01-19 03:21

    You can use ADO.NET to read values from an Excel sheet. For more information on the connection string, see http://www.connectionstrings.com/excel-2007

    
        
    
    

    You can then use a standard System.Data.OleDb.OleDbConnection to read values from the data source. For example, consider an Excel file that has a sheet named Users, with two columns, UserName and Age.

    using System.Data;
    using System.Data.Common;
    
    public int UserExists(string userName, int age)
    {
        var provider = ConfigurationManager.ConnectionStrings["Default"].ProviderName;
        var factory = DbProviderFactories.GetFactory(provider);
    
        var connectionString = ConfigurationManager.ConnectionStrings["Default"].ConnectionString;
    
        using (var connection = factory.CreateConnection())
        {
            connection.ConnectionString = connectionString;
    
            using (DbCommand command = connection.CreateCommand())
            {
                DbParameter userNameParameter = factory.CreateParameter();
                userNameParameter.ParameterName = "@UserName";
                userNameParameter.DbType = DbType.String;
                userNameParameter.Direction = ParameterDirection.Input;
                userNameParameter.IsNullable = false;
                userNameParameter.Value = userName;
    
    
                DbParameter ageParameter = factory.CreateParameter();
                ageParameter.ParameterName = "@Age";
                ageParameter.DbType = DbType.Int32;
                ageParameter.Direction = ParameterDirection.Input;
                ageParameter.IsNullable = false;
                ageParameter.Value = age;
    
                command.CommandText = "SELECT COUNT(*) FROM [Users$] WHERE UserName=@UserName AND Age=@Age";
                command.Parameters.Add(userNameParameter);
                command.Parameters.Add(ageParameter);
                connection.Open();
    
                int usersExits = (int) command.ExecuteScalar();
    
                return usersExits == 1;
            }
        }
    }
    

提交回复
热议问题