java poi 查找字符串,Java的POI:如何找到一个字符串值的Excel单元格并获取其位置(行)使用该位置找到另一个小区...

I'm looking for a cell in a spreadsheet that has the string 'Total' and then use the row in which that cell is to find the total value in another cell which is always the same cell/column (the 10th cell in a 0 based index).

I have the following code, which has no errors (syntax), but the findCell method is not returning rowNum value:

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);

}

}

解决方案

This method fix is the solution to your problem:

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;

}

Keep in mind that your colnr is still a fixed value.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值