从C#中的Excel文件获取行

我正在通过C#中的Excel文件阅读。 文件中有3张:

  1. 概要
  2. 用户
  3. 其他

我正在循环显示汇总表的各列(代码如下)

在每张表中都有一个SummaryIDSummaryID

 foreach (DataColumn dc in Summary.Columns) { foreach (DataRow dr in Summary.AsEnumerable()) { //get column SummaryID for everyrow //And then get all rows in Users sheet that match SummaryID //And then get all rows in Others sheet that match SummaryID } } 

我的问题是: 对于汇总表(SummaryID)中的每一行,我想获取与“用户”和“其他”表中的SummaryID匹配的所有匹配行

注意: SummaryID列全部存在3张,是所有工作表中的第一列。

我喜欢使用LinqToExcel他们有一个LinqToExcel.Row类可能会帮助你,你将使用LINQ over foreach语句。

你有没有考虑过像数据库一样处理你的Excel工作表,并使用OLEDB或类似的技术查询你想要的数据?

这将是一个简单的Join查询在这一点上 – 可能会更快…

你可以使用OleDB来做到这一点。 代码是类似的

  // create a connection to your excel file // the 8.0 denotes excel 2003 // you will need to use the right number for your version of excel OleDbConnection con = new OleDbConnection( @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=InsertYourFile.xls"; Extended Properties=Excel 8.0" ); // create a new blank datatableDataTable dtSheets = new DataTable(); // create a data adapter to select everything from the worksheet you want OleDbDataAdapter da = new OleDbDataAdapter( "select * from [YourWorksheetName$] WHERE BLAH, etc", con ); // use the data adapter to fill the datatable da.Fill( dtSheets );