简体   繁体   English

从该行中找到特定的字符串后,如何打印整个Excel工作表行?

[英]How to print the whole row of an excel sheet after finding a specific string from that row?

This is the code I am using to find the specific string in an excel sheet. 这是我用来在Excel工作表中查找特定字符串的代码。

FileInputStream fis = new FileInputStream(new File("D:\\excel_file.xlsx"));
workbook = new XSSFWorkbook(fis);

for(int i = 0; i < workbook.getNumberOfSheets(); i++) {
    XSSFSheet spreadsheet = workbook.getSheetAt(i);
    Iterator<Row> rowIterator = spreadsheet.iterator();
    while (rowIterator.hasNext()) {
        row = (XSSFRow) rowIterator.next();
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()) {
            Cell cell = cellIterator.next();

            String test_string = "search_phrase";
            if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                if (test_string.trim().equalsIgnoreCase(cell.getStringCellValue().trim())) {
                    flag = 1;
                    rowNum = row.getRowNum();
                    System.out.println("found");
                }
            }
        }
        fis.close();
        workbook.close();
    }
}

if(flag==0) {
    System.out.println("not found");
}

I can also get the row number easily. 我也可以轻松获得行号。

But using that row number I am not able to figure out how to get all the cells in that row. 但是使用该行号我无法弄清楚如何获取该行中的所有单元格。

No need to find row number. 无需查找行号。 If the condition met and, you have row then you can use the following in place of Flag=1; 如果满足条件,并且有row则可以使用以下内容代替Flag=1;

Iterator<Cell> cellItr = row.iterator();
    while(cellItr.hasNext()){
        System.out.println(cellItr.next().toString());
    }

However I am assuming the datatype in the cell are String. 但是我假设单元格中的数据类型是String。 If not, you need to manage the cell data type and missingCellPolicy for perfection. 如果不是,则需要管理单元格数据类型和missingCellPolicy以实现完美。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM