POI对公式的支持
2009年11月26日 09:48:00 山巅 阅读数:7078 标签: stringc 更多
个人分类: POI
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/shandian534/article/details/4876018
一、写入公式:
1、取得单元格 cell = contentRow.createCell(6);
2、设置单元格的类型为公式 cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
3、设置单元格的样式 cell.setCellStyle(excelUtil.getDoubleStyle(workbook));
4、设置单元格的公式 cell.setCellFormula("SUM(G3:G"+startRow+")");
二、读出公式:
FileInputStream fis = new FileInputStream("c:/temp/test.xls");
Workbook wb = new HSSFWorkbook(fis); //or new XSSFWorkbook("c:/temp/test.xls")
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
// suppose your formula is in B3
CellReference cellReference = new CellReference("B3");
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cellValue.getNumberValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cellValue.getStringValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case Cell.CELL_TYPE_FORMULA:
break;
}