在foreach Excel互操作中查找包含两个值的行

时间:2017-05-12 04:49:04

标签: c# .net excel

如何使用Excel互操作在excel表中找到行而不必遍历每一行?我想使用foreach语句循环我的集合,并且存在employeeId和费用号码,我想更新该员工的总小时数和费用数。

这是我目前的代码,但男人很慢!!

我可以使用excel范围来查找包含employeeId和费用编号的行来代替嵌套的for循环吗?

var lastLine = sheet.UsedRange.Rows.Count; 

foreach (var timeEntry in filteredList.OrderBy(x =>int.Parse(x.ChargeNumber.Split('.')[2], CultureInfo.CurrentCulture)))
{
    for (var row = 3; row <= lastLine; row++)  //loop over archive sheet
    {
        if (Convert.ToInt32(timeEntry.EmployeeId) == sheet.Cells[row, 1].Value2 && timeEntry.ChargeNumber == sheet.Cells[row, 5].Text.Trim())
        {
            sheet.Cells[row, 6] = timeEntry.TotalHours;

            if (timeEntry.TimeDifferential > 0)
            {
                sheet.Cells[row, 8] = "Add " + timeEntry.TimeDifferential.ToString(CultureInfo.CurrentCulture) + " from " + previousMonthYear;
            }
            else if (timeEntry.TimeDifferential < 0)
            {
                var normalTime = -(timeEntry.TimeDifferential);

                sheet.Cells[row, 8] = "Subtract " + normalTime.ToString(CultureInfo.CurrentCulture) + " from " + previousMonthYear;
            }
            break;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用Range.Find Method,这比循环更有效。

我还在我的一个excel自动化项目中循环每一行,但它太慢了,所以我使用了Range.Find

根据您的要求修改它。

Range Find(
    Object What,
    Object After,
    Object LookIn,
    Object LookAt,
    Object SearchOrder,
    XlSearchDirection SearchDirection,
    Object MatchCase,
    Object MatchByte,
    Object SearchFormat
)

More info - See it here

Examples