如何从一个Excel工作表使用java获取特定列名称(作为parameter passing)的最后一个非空单元格的行索引?

获取书名,表名和列名作为参数并期望模块返回所需行索引的模块摘要。

public int getExcelData(String WBookName, String sheetName, String columnName) { int colNum = -1; int rowIndex = -1; InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/"+WBookName+".xls"); try { excelWBook = new XSSFWorkbook(inputStream); Log.info(WBookName+"Excel File loaded Successfully"); } catch (IOException e) { Log.fatal("Unable to load"+WBookName+" Excel File"); e.printStackTrace(); } excelWSheet = excelWBook.getSheet(sheetName); row = excelWSheet.getRow(0); for(int i=0; i<row.getLastCellNum();i++) { if(row.getCell(i).getStringCellValue().trim().equals(columnName)){ colNum = i; } } { //code for getting last non-empty row for a columnName (Possible using Iterator?) } return rowIndex; 

由于Apache POI具有方法Sheet#getLastRowNum() ,我将使用for-loop从excelWSheet.getLastRowNum()向后excelWSheet.getLastRowNum() 0并询问每行是否存在值。

代码会是这样的 (你应该自己试试,我现在只是“在浏览器中编程”):

 for (int rowNum = excelWSheet.getLastRowNum(); rowNum >= 0; rowNum--) { final Row row = excelWSheet.getRow(rowNum); if (row != null && row.getCell(colNum) != null) { rowIndex = rowNum; break; } }