C#读取多个Excel文件[关闭]

excel

1个回答

写回答

萍心而论

2025-06-14 07:15

+ 关注

excel
excel

使用C#语言读取多个excel文件是一个常见的需求,本文将介绍如何使用C#编写程序来实现这个功能。

案例代码:

csharp

using System;

using System.IO;

using System.Data;

using excelDataReader;

class Program

{

static void MAIn(string[] args)

{

string[] files = Directory.GetFiles("路径", "*.xlsx"); // 替换为你的文件路径

foreach (string file in files)

{

using (var stream = File.Open(file, FileMode.Open, FileAccess.Read))

{

using (var reader = excelReaderFactory.CreateReader(stream))

{

do

{

while (reader.Read())

{

for (int i = 0; i < reader.FieldCount; i++)</p> {

Console.WriteLine(reader.GetValue(i));

}

}

} while (reader.NextResult());

}

}

}

Console.ReadKey();

}

}

第一步:获取excel文件列表

要读取多个excel文件,首先需要获取文件列表。可以通过 Directory.GetFiles 方法来获取指定路径下的所有excel文件。

csharp

string[] files = Directory.GetFiles("路径", "*.xlsx");

这里的 "路径" 需要替换为你的实际文件路径,"*.xlsx" 表示只获取扩展名为xlsx的文件。

第二步:读取excel文件内容

使用excelDataReader库可以方便地读取excel文件的内容。首先需要引入excelDataReader命名空间,然后使用 excelReaderFactory.CreateReader 方法来创建一个excel读取器。

csharp

using (var stream = File.Open(file, FileMode.Open, FileAccess.Read))

{

using (var reader = excelReaderFactory.CreateReader(stream))

{

// 读取excel文件内容

}

}

在 using 代码块中,我们可以通过 reader.Read() 方法来读取每一行的数据。通过 reader.GetValue(i) 方法来获取每一列的值。

csharp

while (reader.Read())

{

for (int i = 0; i < reader.FieldCount; i++)</p> {

Console.WriteLine(reader.GetValue(i));

}

}

第三步:处理多个工作表

有些excel文件可能包含多个工作表,我们需要处理每个工作表的数据。可以使用 reader.NextResult() 方法来移动到下一个工作表。

csharp

do

{

while (reader.Read())

{

// 处理当前工作表的数据

}

} while (reader.NextResult());

在 do-while 循环中,通过 reader.Read() 方法读取当前工作表的每一行数据。

通过以上步骤,我们可以实现使用C#读取多个excel文件的功能。首先获取excel文件列表,然后逐个打开文件并读取数据,最后处理多个工作表的数据。

参考资料:

- C#读取多个excel文件[关闭]:https://www.cnblogs.com/luogu/p/14414120.html

举报有用(4)分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号