Free Support Forum - aspose.com

How to get multiple cells using find method for particular string pattern

Hi Team,

Following is my code which i am using to get cell matching with string pattern.Here i am trying to find cell which return me Test but it is giving me cell with value Test1.
Can someone tell me how to get all cells having Test in it ?

Excel file content :

Test1
Test2
Test

String result="";
//Creating an Workbook object with an Excel file path
Workbook workbook = new Workbook(“File_Name”);
// Read first excel sheet
Worksheet worksheet = workbook.getWorksheets().get(0);

        // Search area and condition
        FindOptions findOptions = new FindOptions();
        CellArea ca = new CellArea();
        ca.StartRow = 0;
        ca.StartColumn = 0;
        ca.EndRow = 9;
        ca.EndColumn = 5;

        findOptions.setRange(ca);
   
        findOptions.setCaseSensitive(true);

        
        Cells cells=worksheet.getCells();

        
        Cell cell = cells.find("Test", null, findOptions);

        // if cell is null
        if(cell==null){
            System.out.println("result : "+result);
        }
        // Get excel value
         result=cell.getValue().toString().trim();

@aditya46,

Thanks for your query.

Please try the following sample code and provide your feedback.

String result="";
//Creating an Workbook object with an Excel file path
Workbook workbook = null;
try {
    workbook = new Workbook("Book1.xlsx");
} catch (Exception e) {
    e.printStackTrace();
}
// Read first excel sheet
Worksheet worksheet = workbook.getWorksheets().get(0);

// Search area and condition
FindOptions findOptions = new FindOptions();
CellArea ca = new CellArea();
ca.StartRow = 0;
ca.StartColumn = 0;
ca.EndRow = 9;
ca.EndColumn = 5;
findOptions.setRange(ca);
findOptions.setCaseSensitive(true);
Cells cells=worksheet.getCells();
Cell nextCell = null;
do
{
    nextCell = worksheet.getCells().find("Test", nextCell, findOptions);
    if (nextCell == null)
        break;
    else
        System.out.println(nextCell.getValue().toString().trim());

} while (true);

Thank you so much for your quick response !

@aditya46,

Hopefully the suggested code segment sorts out your issue now. Let us know if you still have any issue or queries, we will be happy to assist you soon.

Yes, issue has been fixed with your suggested code.

@aditya46,

Thank you for the feedback.