Fetch the data from Excel using Apache poi using java

后端 未结 1 1031
攒了一身酷
攒了一身酷 2021-01-03 16:44

I need to fetch the Test data from the excel by passing the test case id. If i pass the Test case id as \"TC005\" - i need to get all the column values like Lab name, Lab

相关标签:
1条回答
  • 2021-01-03 17:28

    Thyagu: I am proposing one solution... first you should create a method that find the row having desired first cell value (in your case desired TestCaseID I suppose) and return a RowObject for the same.

    public static HSSFRow findRow(String stringToFind){
                //`hswb` is HSSFWorkbook
        HSSFSheet sheet = hswb.getSheetAt(0);
        Iterator <Row> rowItr = sheet.iterator();
        while(rowItr.hasNext()){
            HSSFRow row = (HSSFRow) rowItr.next();
            if(row.getCell(0).toString().equalsIgnoreCase(stringToFind)){
                return row;
            }
        }
      // If no such row found need to handle NullPointerException for that
        return null;
    }
    

    Once you have the correct RowObject you can extract any non empty cell value from that or can do whatever you want, like in this case I have just printed the same.

        public static void getAllColumnFromRow(HSSFRow RowObject){
        Iterator<Cell> itr = RowObject.iterator();
        HSSFRow headerRow = RowObject.getSheet().getRow(0);
        String cellValue = "";
        String information = "";
        int headerCellCount = 0;
        //to avoid first column
        itr.next();
    
        while(itr.hasNext()){
            Cell cell = itr.next();
            Cell headerValue = headerRow.getCell(headerCellCount++);
            switch(cell.getCellType()) {
            case HSSFCell.CELL_TYPE_BOOLEAN:
                cellValue = cell.getBooleanCellValue() +"";
                information = information + " " +headerValue+" - "+cellValue+ "; ";
                break;
            case HSSFCell.CELL_TYPE_NUMERIC:
                cellValue = cell.getNumericCellValue() + "";
                information = information + " " +headerValue+" - "+cellValue+ "; ";
                break;
            case HSSFCell.CELL_TYPE_STRING:
                cellValue = cell.getStringCellValue();
                information = information + " " +headerValue+" - "+cellValue+ "; ";
                break;
            case HSSFCell.CELL_TYPE_BLANK:
                break;
            }
        }
        System.out.println(information);
    }
    

    In case if any possibility to get a null cell within the last cell values of any row, you need to use MissingCellPolicy.

    0 讨论(0)
提交回复
热议问题