转载

Java POI:如何查找具有字符串值的Excel单元格并获取其位置(行)以使用该位置查找另一个单元格

我正在寻找一个包含字符串’Total’的电子表格中的单元格,然后使用该单元格所在的行来查找另一个单元格中的总值,该单元格始终是相同的单元格/列(0中的第10个单元格)基于索引).

我有以下代码,没有错误(语法),但findCell方法没有返回rowNum值:

public static void main(String[] args) throws IOException{

        String fileName = "C://file-path//report.xls";
        String cellContent = "Total";
        int rownr=0, colnr = 10;

        InputStream input = new FileInputStream(fileName);

        HSSFWorkbook wb = new HSSFWorkbook(input);
        HSSFSheet sheet = wb.getSheetAt(0);

        rownr = findRow(sheet, cellContent);

        output(sheet, rownr, colnr);

        finish();
    }

    private static void output(HSSFSheet sheet, int rownr, int colnr) {
        /*
         * This method displays the total value of the month
         */

        HSSFRow row = sheet.getRow(rownr);
        HSSFCell cell = row.getCell(colnr);

                System.out.println("Your total is: " + cell);           
    }

    private static int findRow(HSSFSheet sheet, String cellContent){
        /*
         *  This is the method to find the row number
         */

        int rowNum = 0; 

        for(Row row : sheet) {
            for(Cell cell : row) {

                while(cell.getCellType() == Cell.CELL_TYPE_STRING){

                    if(cell.getRichStringCellValue().getString () == cellContent);{

                            rowNum = row.getRowNum();
                            return rowNum;  
                    }
                }
            }
        }               
        return rowNum;
    }

    private static void finish() {

        System.exit(0);
    }
}

此方法修复是您的问题的解决方案:

private static int findRow(HSSFSheet sheet, String cellContent) {
    for (Row row : sheet) {
        for (Cell cell : row) {
            if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
                if (cell.getRichStringCellValue().getString().trim().equals(cellContent)) {
                    return row.getRowNum();  
                }
            }
        }
    }               
    return 0;
}

请记住,您的colnr仍然是固定值.

翻译自:https://stackoverflow.com/questions/9049995/java-poi-how-to-find-an-excel-cell-with-a-string-value-and-get-its-position-ro

原文  https://codeday.me/bug/20190112/522065.html
正文到此结束
Loading...