问题描述
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
仍然是一个固定值。
解决方法
我正在电子表格中查找具有字符串’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);
}
}