【问题标题】:Java excel: How to compare two cellsJava excel:如何比较两个单元格
【发布时间】:2017-05-31 17:47:37
【问题描述】:

我正在查看每一行的第 1 列的值是否相同或不同我尝试将 .getContents() 添加到单元格和工作表的末尾,但它不会改变结果并尝试转换它们都是字符串,但结果仍然相同。每次我尝试它都会返回“do action 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
                 }
             }

【问题讨论】:

    标签: java excel


    【解决方案1】:

    使用Apache POI:

    首先:您正在比较两个不同的单元格,不是它们的内容,这就是为什么总是执行动作 2。要获取他们的内容,您可以说:

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

    String content = cell.getStringCellValue();
    

    第一个代码 sn-p 的优点是,单元格的内容不必是字符串,也可以是数字,不会抛出异常。

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

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

    【讨论】:

    • 你让我走上了正确的道路,但我发现工作正在使用:if(cellOne.getContents().equals(cellTwo.getContents())){
    【解决方案2】:

    所以要让它工作,我必须让 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
                         }
                     }
    

    【讨论】:

      猜你喜欢
      • 2019-12-22
      • 1970-01-01
      • 2012-05-21
      • 1970-01-01
      • 1970-01-01
      • 2022-11-03
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多