2017-05-31 153 views
1

我期待看到每行如果列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 
       } 
      } 

回答

1

使用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

很好看,現在對你的作品 –

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 
        } 
       }