You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Java POI中设置公式计算后单元格内容的格式

Java POI公式单元格格式设置问题解决

我正在开发一个Java POI应用,用于遍历交易列表,通过单元格间数值相减计算Net FC净金额(逻辑和Excel公式计算一致)。目前公式计算功能正常,但无法为公式所在的I、J列(对应代码中索引8、9的单元格)设置统一的右对齐且保留两位小数的格式。

我尝试了以下自定义CellStyle的代码,但生成的Excel中公式单元格格式不符合预期:

private CellStyle getCellStyle(String fname, int size, boolean isbold, String align) {
    CellStyle style = workbook.createCellStyle();
    switch(align) {
        case "L" : {style.setAlignment(HorizontalAlignment.LEFT); break;}
        case "C" : {style.setAlignment(HorizontalAlignment.CENTER); break;}
        case "R" : {style.setAlignment(HorizontalAlignment.RIGHT); break;}
    }
    style.setFont(getFont(fname, size, isbold));
    return style;
}

private void writeRows() {
    int row = 0;
    String font = "Cordia New";
    Dao.connect();
    TreeMap<Integer, Income> map = Dao.selectIncomesByYear("2023");
    Dao.disconnect();
    Income obj; 
    Iterator<Income> li = map.values().iterator();
    while (li.hasNext()) {
        obj = li.next();
        row++;
        XSSFRow dataRow = sheet.createRow(row);   

        XSSFCell cell = dataRow.createCell(0);
        cell.setCellStyle(getCellStyle(font, 13, false, "C"));
        cell.setCellValue(getPaymentDate(obj.getPymtDate()));  

        cell = dataRow.createCell(1);
        cell.setCellStyle(getCellStyle(font, 13, false, "L"));
        cell.setCellValue(getSecurityName(obj.getSecCode()));

        …
        
        cell = dataRow.createCell(7);
        String wtax = DecimalFormatter.formatAmount(obj.getWholdTax(), 2, '.');
        cell.setCellStyle(getCellStyle(font, 13, false, "R"));
        cell.setCellValue(wtax);
        
        FormulaEvaluator evaluator =    
            workbook.getCreationHelper().createFormulaEvaluator();
        
        dataRow.createCell(8).setCellFormula(getFormula8(row + 1));
        dataRow.createCell(9).setCellFormula(getFormula9(row + 1));
    }
}

之后我从一篇10年前的帖子中找到解决方案,步骤如下:

  • 创建org.apache.poi.ss.usermodel.CreationHelper实例:
CreationHelper createHelper = workbook.getCreationHelper();
  • 为公式单元格设置公式后,通过该助手应用完整格式(同时保留右对齐、字体样式和两位小数):
// 处理I列(索引8)单元格
dataRow.createCell(8).setCellFormula(getFormula8(row + 1));
XSSFCell cellI = dataRow.getCell(8);
CellStyle cellStyle = workbook.createCellStyle();
// 复用之前定义的右对齐+指定字体样式
cellStyle.cloneStyleFrom(getCellStyle(font, 13, false, "R"));
// 设置保留两位小数的数据格式
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("0.00"));
cellI.setCellStyle(cellStyle);

// 处理J列(索引9)单元格,直接复用已创建的样式
dataRow.createCell(9).setCellFormula(getFormula9(row + 1));
XSSFCell cellJ = dataRow.getCell(9);
cellJ.setCellStyle(cellStyle);

说明:若仅设置数据格式会丢失原有的对齐和字体配置,通过cloneStyleFrom复用自定义样式后再添加小数格式,可同时满足所有格式要求。

内容的提问来源于stack exchange,提问作者Rusty

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 22:05:38