using System; using System.Data; using System.Data.OleDb; using System.Collections.Generic; using System.Text; namespace Excelcalling1 { class Program { static void Main(string[] args) { string ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=E:\SheetForTest.xls;Integrated Security=SSPI; Extended Properties=Microsoft Excel 11.0 Object Library"; //Create the connection System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection (ConnectionString); //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$]"; // 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(); try { ExcelConnection.Open(); } catch (OleDbException e) { string errorMessages = ""; for (int i = 0; i < e.Errors.Count; i++) { errorMessages += "Index #" + i + "\n" + "Message: " + e.Errors[i].Message + "\n" + "NativeError: " + e.Errors[i].NativeError + "\n" + "Source: " + e.Errors[i].Source + "\n" + "SQLState: " + e.Errors[i].SQLState + "\n"; } System.Diagnostics.EventLog log = new System.Diagnostics.EventLog(); log.Source = "My Application"; log.WriteEntry(errorMessages); Console.WriteLine("An exception occurred. Please contact your system administrator."); } //Create a reader System.Data.OleDb.OleDbDataReader ExcelReader; ExcelReader = ExcelCommand.ExecuteReader(); //For each row after the first //Message box the values in the first column i.e. column 0 while (ExcelReader.Read()) { //MessageBox.Show((ExcelReader.GetValue(0)).ToString()); Console.WriteLine("value retrieved!!"); } ExcelConnection.Close(); } } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)