java - Apache poi 通过公式填充单元格值

标签 java excel apache-poi

我是 apache poi 的新手,尝试编写 excel 文件,但在将公式设置为单元格时遇到了一些问题。

下面是我的示例 excel:

<表类="s-表"> <头> 用户 国家 值 <正文> 罗希特 英国 约翰 IND

我需要根据User 填充Value 列>国家/地区 字段。下面是我想转换成 apache poi java 的 excel 公式

=IF(AND(LEN([@[User]]) > 0, [@Country] = "UK"),1,0)

谁能帮帮我?

示例代码

try {
        InputStream inputStream = this.getClass().getResourceAsStream("/sample.xlsx");
        XSSFWorkbook workbook = new XSSFWorkbook (inputStream);
        System.out.println("inside the controller");
        XSSFSheet sheet = workbook.getSheetAt(0);
        Object[][] bookData = {
                {"Rohit","UK",null},
                {"John","IND",null}                   
        };

        int rowCount = sheet.getLastRowNum();
        int count=0;
        //CellStyle cell1;
        for (Object[] aBook : bookData) {
            Row row = sheet.createRow(++rowCount);

            int columnCount = 0;

            Cell cell = row.createCell(columnCount);
            // cell.setCellValue(rowCount);

            for (Object field : aBook) {
                cell = row.createCell(columnCount++);
                if(field==null){
                    cell.setCellFormula("IF(AND(LEN(A1:A3)>0,(B1:B3)=UK),1,0)"); 
                }
                else if (field instanceof String) {
                  cell.setCellValue((String) field);
                } else if (field instanceof Integer) {
                    cell.setCellValue((Integer) field);
                }
            }
        }

       java.util.List<XSSFTable> l = sheet.getTables();
        l.get(0).getCTTable().setRef("A1:L4");

       FileOutputStream outputStream = new FileOutputStream("D://demo/sample_with_values.xlsx");
        workbook.write(outputStream);
        workbook.close();
        outputStream.close();

    } catch (IOException | EncryptedDocumentException ex) {
        ex.printStackTrace();
    }

最佳答案

正如 @Axel Richter 提到的那样,使用 == 是无效的。

cell.setCellFormula("IF(AND(LEN(A1:A3)>0,(B1:B3)==UK),1,0)");

您的公式有误。

#1.错误...

Parse error near char 25 '=' in specified formula 'IF(AND(LEN(A1:A3)>0,(B1:B3)==UK),1,0)'. Expected cell ref or constant literal` 

…表示您在公式中使用了额外的 =

#2. (B1:B3)==UK 应该是 (B1:B3)="UK"。您正在比较一个字符串值,因此它应该用双引号引起来。

代码:

cell.setCellFormula("IF(AND(LEN(A1:A3)>0,(B1:B3)=\"UK\"),1,0)");

输出:

enter image description here

关于java - Apache poi 通过公式填充单元格值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70891907/

相关文章:

apache-poi - Apache poi-3.10-FINAL-20140208.jar 下载链接

java - 如何为服务器中的文件添加静态资源位置,但与应用程序所在的服务器不同

java - 灵活的界面设计模式

excel - 在 VBA 中按空格过滤

vba - 424 错误 需要对象

excel - 不带引号显示前导零

java - 使用 Apache POI 向 Powerpoint 幻灯片添加注释

java - 是否有任何Bigdata工具来处理pdf文档

java - 如何在没有 spring security 的情况下使用 api key 保护其余 api

java - setBoldweight 不起作用