Find a string in a Range using ClosedXML C#
Asked Answered
D

1

5

I want to be able to find if a particular string exists in a range using ClosedXML, however, I cannot find any find command in the documentation. Currently I loop through 1000s of rows to find if the string exists. Is there a more efficient way to do this?

Here is an example of my code:

for (int j = 3; j <= PipeSheet.LastRowUsed().RowNumber(); j ++)
{
     if ((PipeSheet.Cell(j, ProdCodeColumnInPipe).Value.ToString().Trim() == SheetToEdit.Cell(i, ProdCodeColumnInMain).Value.ToString().Trim() & PipeSheet.Cell(j, 3).Value.ToString().Trim() == SheetToEdit.Cell(i, RegionCodeInMain).Value.ToString().Trim()))
     {
           SheetToEdit.Cell(i, ColumnToEdit).Value = "+";

           if ((new[] { "Open", "Under Review" }).Contains(PipeSheet.Cell(j, 5).Value.ToString().Trim()) & (new[] { "Forecast"}).Contains(PipeSheet.Cell(j, 4).Value.ToString().Trim()))
           {
                  if (FirstColumnHighlight > 1 & LastColumnHighlight > 1)
                  {
                        for (int k = FirstColumnHighlight; k <= LastColumnHighlight; k++)
                        {
                              SheetToEdit.Cell(i, k).Style.Fill.BackgroundColor = XLColor.FromArgb(255, 255, 0);
                        }
                  }
           }
    }
}
Devastating answered 9/5, 2017 at 19:33 Comment(0)
S
15

Firstly, your goal is best solved using conditional formatting.

But to answer your question, you can search for a string:

sheet.CellsUsed(cell => cell.GetString() == searchstring)

Reference: https://github.com/ClosedXML/ClosedXML/wiki/Better-lambdas

-- UPDATE --

There is a pull request at https://github.com/ClosedXML/ClosedXML/pull/399 to help with this, for example:

 foundCells = ws.Search("searchText", CompareOptions.OrdinalIgnoreCase);
Shadoof answered 10/5, 2017 at 13:50 Comment(5)
TY Francois, I might be able to use both ideas to speed up my procedure. However, just curious that code what does it return? It doesn't seem to return a cell. So how would I get the row number from that?Devastating
@Devastating It returns IEnumerable<IXLCell>, i.e. all the cells that match your search predicate.Shadoof
how can I then loop through them? so then I can do another test? Ty for all your help.Devastating
@Devastating You're best off asking general programming questions in another post.Shadoof
To answer the loop question, you can use Linq. (Ensure System.Core is referenced and a using System.Linq statement is added to your code). In my case I only wanted the first value found so using the above example: foundCells = ws.Search("searchText", CompareOptions.OrdinalIgnoreCase).FirstOrDefault().Value.ToString(); Juliettejulina

© 2022 - 2024 — McMap. All rights reserved.