Linq to Excel – 仅接收来自sheet1中最后一行的数据

在尝试使用ADO.NET查询Excel电子表格之后,我决定在我的项目中尝试使用Linq到Excel 。

我创build了一个方法,它应该返回列B的值,当我提供相应的列A(两个在同一行)的值。 Sheet1有一个标题行或至less一行,指示列A和B是什么。

当我将我的代码与一个基本的linq查询结合起来检索数据时,我只能从最后一行获取数据,而不pipe列AI中的值是什么。 它总是最后一排。 在我的工作表中有1159行。 电子表格是Excel 2010,所以数据引擎应该是我所设想的ACE。

这是我的代码…

public static string ReturnDefinition(string remCode) { string strReturnMessage = ""; string pathToExcelFile = @"MEDICARE.xlsx"; string sheetName = "sheet1"; var excelFile = new ExcelQueryFactory(pathToExcelFile); var codeDescriptions = from a in excelFile.Worksheet(sheetName) select a; try { foreach (var a in codeDescriptions) { if (a["Code"].ToString().Contains(remCode)) { strReturnMessage = a["Description"].ToString(); } else { strReturnMessage = "No Data"; } } return strReturnMessage; } catch (Exception ex) { return "Error: " + ex.Message; } finally { } } 

有任何想法吗?

更新

看来我找不到结果。 这与查找结果时不会跳出循环有关。 循环每次都会持续到最后的结果。

当你find你正在寻找的东西的时候,你应该直接返回值,否则它会继续循环,这个值将会是最后find的或者没有数据。

 strReturnMessage = a["Description"].ToString(); return strReturnMessage; 

你不需要别的东西; 只有当循环完成而没有find值,你会返回“无数据”:

  strReturnMessage = a["Description"].ToString(); return strReturnMessage; } // end of if } // end of loop return "No Data"; 

如果你想要最后描述,其中代码包含search文本,那么:

  strReturnMessage = a["Description"].ToString(); } // end of if } // end of loop if (strReturnMessage == "") { return "No Data"; } else { return strReturnMessage; } 

我想推荐另一个有用的软件包:

http://nugetmusthaves.com/Package/EPPlus

至于我最好的一个。 在你的情况下,我没有经验。