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

问题描述:

我期待看到每行如果列1的值是相同或不同我已尝试将.getContents()添加到单元格和工作表的末尾,但它doesn不改变结果,并试图将它们都转换为字符串,但仍然是相同的结果。每次我已经试过一次回国不断 “做动作2”Java excel:如何比较两个单元格

我还使用了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(); 

第一代码片段的好处是,一个单元格的内容并不一定是一个字符串,它们也可以是数字,而不会抛出异常。

第二个:您必须使用.equals(Object)方法而不是==运算符,因为您要比较的两个字符串永远不会是字面上相同的对象。另外你的第二个如果是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 
    } 
} 
+0

你把我在正确的轨道上,但我发现,工作是使用: 如果(cellOne.getContents()等于(cellTwo.getContents())){ – bigbangben

+0

很好看,现在对你的作品 –

因此,要得到它的工作,我不得不让cell.getcontents()返回的字符串值,然后用.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 
        } 
       }