【问题标题】:Java/Apache POI - Formula aren't setting on cell correctlyJava/Apache POI - 单元格上的公式设置不正确
【发布时间】:2018-05-12 03:46:18
【问题描述】:

我有一个 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, \"<>\")");

【问题讨论】:

标签: java excel excel-formula apache-poi


【解决方案1】:

在这种情况下,它应该用英文书写。就像 CONTSE 将成为:COUNTIF。 SOMA 将是 SUM.. 等等。只需搜索英文版的公式即可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多