Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find Excel Cell by Text in Apache POI

I'd like to find a cell in an Excel sheet by its text. The text is something like %t:

sheet.findCell("%t"); // pseudo-code, not working

My goal is to enable the user to provide kind of template, in which data is written. Colours and fonts, as well as data's position can be configured by the user in an Excel file. This %t cell is the top-left corner of the data table.

Additional question: Is there a more elegant way to get this job done?

EDIT I'm iterating over the rows and cells to find it. I'm afraid it's not really efficient, but it works so far:

public static Cell findCell(XSSFSheet sheet, String text) {     
    for(Row row : sheet) {          
        for(Cell cell : row) {              
            if(text.equals(cell.getStringCellValue()))
                return cell;
        }
    }       
    return null;
}
like image 863
Matthias Meid Avatar asked Sep 01 '10 13:09

Matthias Meid


People also ask

How do I get cell type in Apache POI?

Apache POI uses the Workbook interface to represent an Excel file. It also uses Sheet, Row, and Cell interfaces to model different levels of elements in an Excel file. At the Cell level, we can use its getCellType() method to get the cell type.

How do you find the value of a string from a numeric cell?

In Excel sheet before entering a numeric value inside a cell ,enter ~ symbol(tild) and enter the value. For Example: ~123. This might help you. You can use a POI DataFormatter to automatically convert any Cell type to String.


2 Answers

You can iterate through the cells of the sheet and investigate the contents. I don't think there is an easier method.

like image 72
Thorbjørn Ravn Andersen Avatar answered Sep 21 '22 02:09

Thorbjørn Ravn Andersen


Its an old post but still i want to publish my code. You can define a file path.

String inputFile = "src\main\resources\file.xlsx";

XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream(inputFile));
                DataFormatter formatter = new DataFormatter();
                for (XSSFSheet sheet : xssfWorkbook) {
                    for (Row row : sheet) {
                        for (Cell cell : row) {
                            if (formatter.formatCellValue(cell).contains("name")){
                                cell.setCellValue("test");
                            }
                        }
                    }
                }
                xssfWorkbook.write(new FileOutputStream(inputFile));
like image 31
buseodaci Avatar answered Sep 20 '22 02:09

buseodaci