C#中怎么使用OleDbConnection连接读取Excel

在C#中使用OleDbConnection连接读取Excel文件,可以按照以下步骤进行操作:

引入System.Data.OleDb命名空间。

using System.Data.OleDb;

创建一个OleDbConnection对象,并设置连接字符串。

string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<Excel文件路径>;Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";
OleDbConnection connection = new OleDbConnection(connectionString);

在连接字符串中,Provider指定了使用的OleDb提供程序,Data Source指定了Excel文件的路径,Extended Properties指定了Excel文件的属性,如版本、是否包含标题等。

打开连接。

connection.Open();

创建一个OleDbCommand对象,并设置SQL查询语句。

string sql = "SELECT * FROM [Sheet1$]";
OleDbCommand command = new OleDbCommand(sql, connection);

这里的Sheet1是Excel文件中的工作表名称。

执行查询,并获取查询结果。

OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 处理查询结果
}

关闭连接。

connection.Close();

完整的示例代码如下:

using System.Data.OleDb;
namespace ReadExcel
{
class Program
{
static void Main(string[] args)
{
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=<Excel文件路径>;Extended Properties='Excel 12.0;HDR=YES;IMEX=1';";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
string sql = "SELECT * FROM [Sheet1$]";
OleDbCommand command = new OleDbCommand(sql, connection);
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 处理查询结果
}
connection.Close();
}
}
}

注意:在使用OleDbConnection连接读取Excel文件时,需要确保计算机上已安装适当的驱动程序。例如,读取.xlsx文件需要安装Microsoft Access Database Engine。

阅读剩余
THE END