请给我一段代码,将excel内容读取到一个List中
时间: 2024-02-24 13:53:48 浏览: 20
好的,以下是一个简单的示例代码,可以将 Excel 文件中的内容读取到 List 中:
```csharp
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
namespace ReadExcelToList
{
class Program
{
static void Main(string[] args)
{
// Excel 文件路径
string filePath = @"C:\example.xlsx";
// 连接字符串
string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
// 建立 OleDbConnection 对象
OleDbConnection conn = new OleDbConnection(connString);
try
{
// 打开连接
conn.Open();
// 查询语句
string sql = "SELECT * FROM [Sheet1$]";
// 建立 OleDbCommand 对象
OleDbCommand cmd = new OleDbCommand(sql, conn);
// 建立 OleDbDataAdapter 对象
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
// 建立 DataTable 对象
DataTable dt = new DataTable();
// 填充 DataTable
adapter.Fill(dt);
// 建立 List 对象
List<string> list = new List<string>();
// 遍历 DataTable,将每一行的内容加入 List
foreach (DataRow row in dt.Rows)
{
string str = "";
for (int i = 0; i < dt.Columns.Count; i++)
{
str += row[i].ToString() + ",";
}
list.Add(str.TrimEnd(','));
}
// 输出 List 中的内容
foreach (string str in list)
{
Console.WriteLine(str);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
// 关闭连接
conn.Close();
}
Console.ReadKey();
}
}
}
```
这段代码使用了 OleDbConnection 和 OleDbDataAdapter 来连接 Excel 文件,并将查询结果填充到 DataTable 中,然后将 DataTable 中的内容遍历加入到 List 中。这里假设 Excel 文件中的数据在 Sheet1 中,如果需要读取其他 Sheet 的数据,只需要修改查询语句中的 Sheet 名称即可。