Read Excel Files with C# OleDbConnection

The steps to connecting and reading an Excel file using OleDbConnection are as follows:

  1. Firstly, make sure that you have referenced the System.Data.OleDb namespace in your project.
  2. Create an OleDbConnection object, specifying the connection string in the format of “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=file path;Extended Properties=Excel 12.0;”. Here, Data Source represents the path to the Excel file.
using System.Data.OleDb;

string connectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\example.xlsx;Extended Properties=Excel 12.0;";
OleDbConnection connection = new OleDbConnection(connectionString);
  1. Open the connection and run an SQL query to retrieve data from the Excel file.
connection.Open();
string query = "SELECT * FROM [Sheet1$]";
OleDbCommand command = new OleDbCommand(query, connection);
OleDbDataReader reader = command.ExecuteReader();
  1. Iterate through the OleDbDataReader object to retrieve data from an Excel file.
while (reader.Read())
{
    // 通过reader["列名"]来获取对应列的数据
    string data = reader["ColumnName"].ToString();
    // 处理数据
}
  1. Finally, disconnect.
reader.Close();
connection.Close();

The above are the basic steps for connecting and reading an Excel file using OleDbConnection. In practical applications, further data processing and operations can be performed as needed.

bannerAds