Thursday, May 28, 2009

Reading Excell Sheet Using Data Connection (Ado.Net)

You want to connect to a Microsoft Excel workbook.
Use the OLE DB .NET data provider.
The solution creates and opens a connection to a Microsoft Excel workbook using the OLE DB .NET data provider. Information about the connection is displayed.

code sample
using System;
using System.Data;
using System.Data.OleDb;
namespace ConnectExcel
{
class Program
{
static void Main(string[] args)
{
// Define connection strings for both default
// Excel .xlsx format and Excel 97-2003 .xls format
string[] oledbConnectString = new string[]
{
"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data Source=..\..\..\Category.xlsx;" +
"Extended Properties=\"Excel 12.0;HDR=YES\";",
"Provider=Microsoft.ACE.OLEDB.12.0;" +
@"Data Source=..\..\..\Category.xls;" +
"Extended Properties=\"Excel 8.0;HDR=YES\";"
};
foreach (string connectString in oledbConnectString)
{
// Define and open the connection
OleDbConnection connection =
new OleDbConnection(connectString);
connection.Open( );
// Output some connection properties to the console
Console.WriteLine("---CONNECTION---");
Console.WriteLine("Connection.String = {0}\n",
connectString);
Console.WriteLine("Connection.State = {0}",
connection.State);
Console.WriteLine("Connection.Provider = {0}",
connection.Provider);
Console.WriteLine("Connection.ServerVersion = {0}",
connection.ServerVersion);
connection.Close( );
Console.WriteLine( );
}
Console.WriteLine("Press any key to continue.");
Console.ReadKey( );
}
}
}

No comments:

Post a Comment