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

我在电子表格中寻找一个string为'Total'的单元格,然后使用该单元格的行来查找总是同一个单元格/列的另一个单元格中的总值(第0个单元格为0基于索引)。

我有以下代码,它没有错误(语法),但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); } } 

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

 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中还有其他Celltypes。 尝试在这些行上放置断点,并检查它们是否具有正确的CellType。