Retrieving Data from a Microsoft Excel Workbook : Excel « ADO.Net « C# / CSharp Tutorial






using System;
using System.Data;
using System.Data.OleDb;

    class Program
    {
        static void Main(string[] args)
        {
            string oledbConnectString = "Provider=Microsoft.ACE.OLEDB.12.0;" +
                @"Data Source=..\Category.xlsx;" +
                "Extended Properties=\"Excel 12.0;HDR=YES\";";

            string commandText = "SELECT CategoryID, CategoryName, " +
                "Description FROM [Sheet1$]";

            OleDbConnection connection = new OleDbConnection(oledbConnectString);

            OleDbCommand command = new OleDbCommand(commandText, connection);
            connection.Open();
            OleDbDataReader dr = command.ExecuteReader( );
            while (dr.Read()){
                Console.WriteLine(dr["CategoryID"]);
                Console.WriteLine(dr["CategoryName"]);
                Console.WriteLine(dr["Description"]);
            }
            connection.Close( );
        }
    }








32.4.Excel
32.4.1.Connecting to a Microsoft Excel Workbook
32.4.2.Retrieving Data from a Microsoft Excel Workbook