代码之家  ›  专栏  ›  技术社区  ›  Jose

动态FOMUNA POI

  •  0
  • Jose  · 技术社区  · 8 年前

    我有两个值,一个是固定值,一个是动态值,在一个单元格中,一旦创建了excel,用户就必须能够修改它,根据这个修改,一个公式将刷新另一个单元格。

    Double ausencias = 4.0;
    
    Cell cellDesgloseCalendario = rowDesglose.createCell(cellnum++);
    cellDesgloseCalendario.setCellValue(160.0);//value that the user should be able to change later
    
    ////
    String strFormula= "=ausencias/cellDesgloseCalendario";
    cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
    cell.setCellFormula(strFormula);
    Cell cellDesglosePorcentajeAbsentismo = rowDesglose.createCell(cellnum++);
    cellDesglosePorcentajeAbsentismo.setCellFormula(strFormula);
    

    我怎样才能动态地取列的位置:“celldesglosecalendario”(e:“a10”,“b20”),因为它们是用几个循环创建的,而我不知道它们的位置,从而创建一个公式,这个公式就是这个列被我的变量“ausencias”分割的结果。

    1 回复  |  直到 8 年前
        1
  •  2
  •   Axel Richter    8 年前

    手机知道地址。你可以通过 Cell.getAddress . 因此可以将地址连接到公式字符串中。

    但不能在公式字符串中以“=”开头 apache poi 因为这是不可能的。见 Formula Support - basics .

    完整示例:

    import java.io.FileOutputStream;
    
    import org.apache.poi.ss.usermodel.*;
    import org.apache.poi.xssf.usermodel.XSSFWorkbook;
    
    public class CreateExcelFormulaUsingCellAddress {
    
     public static void main(String[] args) throws Exception {
    
      Workbook wb = new XSSFWorkbook();
      Sheet sheet = wb.createSheet();
      Row rowDesglose = sheet.createRow(0);
    
      Double ausencias = 4.0;
    
      int cellnum = 0;
    
      Cell cellDesgloseCalendario = rowDesglose.createCell(cellnum++); // cellDesgloseCalendario is A1
      cellDesgloseCalendario.setCellValue(160.0);
    
      String strFormula = ausencias.toString() + "/" + cellDesgloseCalendario.getAddress().formatAsString();
                       // 4.0                     /    A1
    System.out.println(strFormula); //"4.0/A1"
    
      Cell cellDesglosePorcentajeAbsentismo = rowDesglose.createCell(cellnum++); // cellDesglosePorcentajeAbsentismo is B1
      cellDesglosePorcentajeAbsentismo.setCellFormula(strFormula); //formula in B1 is now =4/A1
    
      wb.write(new FileOutputStream("CreateExcelFormulaUsingCellAddress.xlsx"));
      wb.close();
     }
    
    }
    
    推荐文章