In my excel sheet many cells contain formulas, i don't want to recalculate these formulas when i read the excel with Apache POI.
The way i do that:
if(cell.getCellType() == XSSFCell.CELL_TYPE_FORMULA) {
//System.out.println("Formula is " + cell.getCellFormula());
switch(cell.getCachedFormulaResultType()) {
case XSSFCell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() +" ");
break;
case XSSFCell.CELL_TYPE_STRING:
System.out.print(cell.getRichStringCellValue()+" ");
break;
}
}
This helps me in getting the raw value in the cell. For example if the cell has value 19.5%, this will give me 0.195456 . I want to get the formatted value.
One way to get the formatted value is:
DataFormatter formatter = new DataFormatter();
System.out.print(formatter.formatCellValue(cell));
This works well for regular cells, but for cells with formulas, this actually gets the formula string and displays it, i.e., it does not get the cached value and formats it, rather it just returns the formula string.
Is there a way to format a value after retrieving it from CELL_TYPE_FORMULA
It's possible to directly format the cached value of a cell without using an evaluator. It's useful in case of values that cannot be recalculated because of third party plugin or unavailable external Data in the cell formula.
This code can be used to do that:
final DataFormatter dataFormatter = new DataFormatter();
final CellStyle cellStyle = cell.getCellStyle();
final String formattedValue = dataFormatter.formatRawCellContents(
cell.getNumericCellValue(),
cellStyle.getDataFormat(),
cellStyle.getDataFormatString()
);
System.out.println(formattedValue);
A formatter is still used but the method formatRawCellContents() is called to manually format the cell cached value with its style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With