Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a string in a Range using ClosedXML C#

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);
                        }
                  }
           }
    }
}
like image 868
djblois Avatar asked May 09 '17 19:05

djblois


1 Answers

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);
like image 72
Francois Botha Avatar answered Oct 22 '22 01:10

Francois Botha