我正在电子表格中查找具有字符串“总计”的单元格,然后使用该单元格所在的行在始终为相同单元格/列(第 10 个单元格)的另一个单元格中查找总值在基于 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);
}
}
最佳答案
此方法修复是您问题的解决方案:
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 仍然是一个固定值。
关于Java 兴趣点 : How to find an Excel cell with a string value and get its position (row) to use that position to find another cell,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9049995/