Java POI:如何查找具有字符串值的 Excel 单元格并获取其位置(行)以使用该位置来查找另一个单元格 [英] Java POI: How to find an Excel cell with a string value and get its position (row) to use that position to find another cell

查看:66
本文介绍了Java POI:如何查找具有字符串值的 Excel 单元格并获取其位置(行)以使用该位置来查找另一个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a cell in a spreadsheet that has the string 'Total' and then use the row in which that cell is to find the total value in another cell which is always the same cell/column (the 10th cell in a 0 based index).

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

I have the following code, which has no errors (syntax), but the findCell method is not returning rowNum value:

    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);
    }
}   

推荐答案

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

This method fix is the solution to your problem:

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 仍然是一个固定值.

Keep in mind that your colnr is still a fixed value.

这篇关于Java POI:如何查找具有字符串值的 Excel 单元格并获取其位置(行)以使用该位置来查找另一个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆