温馨提示×

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

小亿
134
2023-08-09 09:48:38
栏目: 编程语言

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

  1. 引入System.Data.OleDb命名空间。
using System.Data.OleDb;
  1. 创建一个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文件的属性,如版本、是否包含标题等。

  1. 打开连接。
connection.Open();
  1. 创建一个OleDbCommand对象,并设置SQL查询语句。
string sql = "SELECT * FROM [Sheet1$]";
OleDbCommand command = new OleDbCommand(sql, connection);

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

  1. 执行查询,并获取查询结果。
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
// 处理查询结果
}
  1. 关闭连接。
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。

0