1

After the headache of attempting to query an Excel spreadsheet with ADO.NET, I've decided to try Linq to Excel in my project.

I have created a method that is supposed to return the value of column B when I provided it with the corresponding value of column A (Both in the same row). Sheet1 has a header row or at least a row indicating what Columns A and B are.

When I combine my code with a basic linq query to retrieve data, I only get data from the last row, no matter what value in column A I ask for. It's alway the last row. There are something like 1159 rows in my sheet. The spreadsheet is Excel 2010, so the data engine should be ACE I presume.

Here is my code...

    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
        {

        }
    }

Any Ideas?

Update

It seems that I am not returning the result when it is found. This has something to do with not breaking out of the loop when the result is found. The loop continues to the last result each time.

4

2 回答 2

1

当您找到您要查找的内容时,您应该立即返回该值,否则它将继续循环,并且该值将是它找到的最后一个值或“无数据”:

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

你不需要其他的;只有当循环完成但没有找到值时,您才会返回“No Data”:

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

return "No Data";

如果您想要 LAST Description,其中 Code 包含搜索文本,则:

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

if (strReturnMessage == "") {
    return "No Data";
} else {
    return strReturnMessage;
}
于 2014-06-02T15:34:13.953 回答
1

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

http://nugetmusthaves.com/Package/EPPlus

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

于 2014-06-02T15:31:16.267 回答