Search code examples
c#excelreturnepplus

How to get the row number if value is in this row and return it


I'm not sure I asked the right question.

Basically I want to go through all rows and check if the Value in Cells[row, 5] = nrNummer. If it does, I want the row number like 30 in realrow and return it. I dont know how to return the number or if "for" is the wrong approach. Below is my code. Maybe someone knows how to do it

private static int GetRowExcel(string projectName)
    {
        using (MemoryStream stream = new MemoryStream(bin))
        using (ExcelPackage excelPackage = new ExcelPackage(stream))
        {
            var ws = excelPackage.Workbook.Worksheets["Work"];

            string nrNummer = projectName.Split(' ').First();
            for (int row = 5; ws.Cells[row, 5].Value != null; row++)
            {
               if(ws.Cells[row, 5].Value.ToString()==nrNummer)
                { int realrow = row;
                }

            }
        }
        return realrow; //The name'realrow' does not exist in the current context
    }

Solution

  • A better approach is to return immediately after you have found your value and not iterate further in the for loop:

    private static int GetRowExcel(string projectName)
        {
            using (MemoryStream stream = new MemoryStream(bin))
            using (ExcelPackage excelPackage = new ExcelPackage(stream))
            {
                var ws = excelPackage.Workbook.Worksheets["Work"];
    
                string nrNummer = projectName.Split(' ').First();
                for (int row = 5; ws.Cells[row, 5].Value != null; row++)
                {
                   if(ws.Cells[row, 5].Value.ToString()==nrNummer)
                    { 
                        return row;
                    }
    
                }
            }
            return -1;  // return any value that shows that row is not found
        }