Java / Apache POI - 公式未在单元格上正确设置

时间:2018-05-11 19:30:15

标签: java excel excel-formula apache-poi

我有一个Java代码,我创建了一个新的.xlsm文件,我创建了一个镜像另一个空的.xlsm文件的格式。我的问题是当我在创建的新.xlsm上的特定单元格中设置公式时。当我打开文件时,单元格显示:#NAME?。但是当我按下单元格中的回车键时,公式会正确显示。当我离开时,公式有效。

为什么会这样?

Java代码如下:

public static String main(String[] args) throws Exception {
      Class.forName("com.mysql.jdbc.Driver");
      Connection connect = DriverManager.getConnection( 
         "jdbc:mysql://localhost:3306/database" , 
         "user" , 
         "password"
      );

      Statement statement = connect.createStatement();
      ResultSet resultSet = statement.executeQuery("select * from `table`");
      FileInputStream file = new FileInputStream(new File("C:\\Users\\Desktop\\Folder1.xlsm"));
      XSSFWorkbook wb = new XSSFWorkbook(OPCPackage.open(file)); 
      XSSFSheet spreadsheet = wb.getSheet("Planilha1");

      XSSFRow row = spreadsheet.createRow(1);
      XSSFCell cell;
      int i = 1;

      while(resultSet.next()) {
         row = spreadsheet.createRow(i);
         cell = row.createCell(1);
         cell.setCellValue("");
         cell = row.createCell(2);
         cell.setCellValue(resultSet.getString("column1"));
         i++;
      }

      XSSFRow linhacontador = spreadsheet.getRow(1);
       if (linhacontador == null) {
        linhacontador = spreadsheet.createRow(1);
       }

      XSSFCell colunacontador = linhacontador.getCell(34);
       if (colunacontador == null) {
        colunacontador = linhacontador.createCell(34);
       }

       colunacontador.setCellType(XSSFCell.CELL_TYPE_FORMULA);
       colunacontador.setCellFormula("CONT.SE(AH:AH, \"<>\")");

      CellRangeAddress range = new CellRangeAddress(1, i-1, 25, 25);
      spreadsheet.addMergedRegion(range);


      FileOutputStream out = new FileOutputStream(new File("C:\\Users\\Desktop\\exceldatabase.xlsm"));
      wb.write(out);
      out.close();
      connect.close();

      return "Worksheet Done!";
   }

显然我的问题在这里:

   colunacontador.setCellType(XSSFCell.CELL_TYPE_FORMULA);
   colunacontador.setCellFormula("CONT.SE(AH:AH, \"<>\")");

1 个答案:

答案 0 :(得分:1)

在这种情况下,它应该用英文写。就像CONTSE一样:COUNTIF。 SOMA将成为SUM ...等等。只是,用英文版搜索公式并且可行。