Java的excel:如何比较两个单元格

我期待看到每行如果列1的值是相同或不同我已经尝试将.getContents()添加到单元格和工作表的末尾,但它不会更改结果,并尝试将它们都转换为string,但仍相同的结果。 每次我尝试它不断返回“做行动2”

我也使用JExcelAPI

w = Workbook.getWorkbook(inputWorkbook); Sheet sheet = w.getSheet(0); for(int i = 1;i<sheet.getRows(); i++){ Cell cell = sheet.getCell(0,i); if(cell == sheet.getCell(0, (i+1))){ //If cell is the same value as the one in the row below it //do action 1 } else if(cell != sheet.getCell(0,(i+1))){//If cell has a different value as the one in the row below it //do action 2 } } 

使用Apache POI :

首先 :你正在比较两个不同的单元格, 而不是它们的内容 ,这就是为什么总是去做行动2 。 要获得他们的内容,你要么说:

 DataFormatter df = new DataFormatter(); String content = df.formatCellValue(cell); 

要么

 String content = cell.getStringCellValue(); 

第一个代码片断的优点是,单元格的内容不一定是一个string,也可以是数字,而不会引发exception。

第二 :您必须使用.equals(Object)方法而不是==运算符,因为您要比较的两个string永远不会是字面上相同的对象。 你的第二个如果是unnessecary。 所以你的代码看起来像这样:

 DataFormatter df = new DataFormatter(); for (int i = 1; i < sheet.getLastRowNum() + 1; i++) { Cell cell = sheet.getRow(i).getCell(i); if (df.formatCellValue(cell).equals(df.formatCellValue(sheet.getRow(i).getCell(0)))) { //If cell is the same value as the one in the row below it //do action 1 } else {//If cell has a different value as the one in the row below it //do action 2 } } 

所以为了得到它的工作,我必须得到cell.getcontents()返回string值,然后使用.equals()比较其他cell2.getContents。

 w = Workbook.getWorkbook(inputWorkbook); Sheet sheet = w.getSheet(0); for(int i = 1;i<sheet.getRows(); i++){ Cell currentCell = sheet.getCell(0,i); Cell nextCell = sheet.getCell(0,(i+1)); if(currentCell.getContents().equals(nextCell.getContents())){ //If cell is the same value as the one in the row below it //do action 1 } else if(!currentCell.getContents().equals(nextCell.getContents())){//If cell has a different value as the one in the row below it //do action 2 } }