JAVA writes data to excel with formulas and obtains formula calculation results

JAVA writes data to excel with formulas and obtains formula calculation results

public static void main(String[] args) throws Exception {
    
    
        String url = "C:\\Users\\LQT\\Desktop\\test.xlsx";
        InputStream in = null;
        try {
    
    
            File file = new File(url);
            if (!file.exists()) {
    
    
                throw new Exception("文件不存在!");
            }
            in = new FileInputStream(file);
            // 读取整个Excel
            XSSFWorkbook workbook = new XSSFWorkbook(in);
            // 获取第一个表单Sheet
            XSSFSheet sheetAt = workbook.getSheetAt(0);
            XSSFRow titleRow = sheetAt.getRow(0);
            titleRow.createCell(0).setCellValue(1);
            titleRow.createCell(1).setCellValue(9);
            sheetAt.setForceFormulaRecalculation(true);
            //后面使用它来执行计算公式 核心代码
            FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
            CellReference cellReference = new CellReference("C1");
            Row row = sheetAt.getRow(cellReference.getRow());
            Cell cell = row.getCell(cellReference.getCol());
            CellValue cellValue = evaluator.evaluate(cell);
            System.out.println(cellValue.getNumberValue());
        }catch (Exception e){
    
    
            e.printStackTrace();
        }finally {
    
    
            try {
    
    
                if(in != null){
    
    
                    in.close();
                }
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

You can create the excel file yourself. The example formula above is: C1=SUM(A1:B1);

Guess you like

Origin blog.csdn.net/weixin_39310051/article/details/128633658