簡體   English   中英

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

我正在尋找一個包含字符串'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仍然是固定值。

if語句后面有一個分號,表示你的if不起作用:

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

即使這不能解決你的問題,我認為你的while聲明可能不適合這里;

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

據我記憶,POI中還有其他Cell類型。 嘗試在這些行上設置斷點並檢查它們是否具有正確的CellType。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM