如何获得两个Excel列的平均值

时间:2019-08-21 13:00:37

标签: java apache-poi

Like this我需要一些帮助来获取xlsx文件的两列平均值的最大值 我可以用jxl做到这一点,但我正在与大型Excel合作。 非常感谢您提供任何答案

public void readExcel() throws BiffException, IOException{//method to read 
contents form excel
    String FilePath = "C:\\Users\\ok.xls";
    double max1=0;
    double max2=0;
    FileInputStream fs = new FileInputStream(FilePath);
    Workbook wb = Workbook.getWorkbook(fs);
    Sheet sh = wb.getSheet(0);// TO get the access to the sheet
    int totalNoOfRows = sh.getRows();// To get the number of rows present in  sheet
 //   int totalNoOfCols = sh.getColumns();// To get the number of columns present in sheet

    for (int row = 0; row < totalNoOfRows; row++)
    {
        firstarray.add(sh.getCell(18, row).getContents());
        secondarray.add(sh.getCell(17, row).getContents());
    }
    for (int row = 0; row < totalNoOfRows; row++)
    {
          if(Double.parseDouble(firstarray.get(row))>=max1 ){
            max1= Double.parseDouble(firstarray.get(row));
    }
          if(Double.parseDouble(secondarray.get(row))>=max2 ){ 
            max2= Double.parseDouble(secondarray.get(row));
      }  
}     double max=(max1 + max2)/2; 
    System.out.println(max);
    }//end of method to read contents from excel

1 个答案:

答案 0 :(得分:2)

您可以通过在放置未使用单元格的公式中使用AVERAGE函数来让Excel做到这一点。然后您对其进行评估并获得结果。

编辑:这是一个代码段。

CellReference cellReference = new CellReference("S1"); // Choose an unused cell here
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol()); 

// Formula that gets average of Q column and R columns' maximums
cell.setCellFormula("AVERAGE(MAX(Q:Q);MAX(R:R))");

// Let Excel do the math
CellValue cellValue = evaluator.evaluate(cell);
System.out.println(cellValue.getNumberValue());