1
Reply

Read a single Cell from Microsoft Excel in c# .NET3.5 using OleDb command

Niraj Doshi

Niraj Doshi

Aug 06, 2008
13.5k
0

    I am very new to C# and .NET Framework. I want to know how to Read Microsoft Excel Cells using OleDb Command. For example I want to read from Sheet 1. I want to read the value of cell of Column A where Cell value of Column B is 5. The code I am using is as follows string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\test.xls; Extended Properties=Excel 8.0"; //Create the connection System.Data.OleDb.OleDbConnection ExcelConnection =new System.Data.OleDb.OleDbConnection(ConnectionString); ExcelConnection.Open(); //create a string for the query string ExcelQuery; //Sheet1 is the sheet name //create the query: //read column with heading A from the Excel file ExcelQuery ="SELECT A FROM [Sheet1$] WHERE B=5"; // from Sheet1"; //use "Select * ... " to select the entire sheet //create the command System.Data.OleDb.OleDbCommand ExcelCommand = new System.Data.OleDb.OleDbCommand(ExcelQuery, ExcelConnection); //Open the connection //ExcelConnection.Open(); //Create a reader System.Data.OleDb.OleDbDataReader ExcelReader; ExcelReader = ExcelCommand.ExecuteReader(); //For each row after the first while (ExcelReader.Read()) { Console.WriteLine((ExcelReader.GetValue(0)).ToString()); } ExcelConnection.Close(); But the problem with this code doesnot execute the line ExcelReader =ExcelCommand.ExecuteReader();

    Niraj Doshi
    August 06, 2008
    0