Java 8 and Apache POI 4.1.x here.
The expected "cell formatting behavior" of Excel, as I've gathered from being an Excel user for most of my life, is as follows:
- There appears to be an underlying "internal value" of a cell, and then there is the "visualization" of that value
- The internal value is a number, value, etc. that is the actual/real value of that cell
- The visualization is an optional way of representing the internal value to the end user
- Example: The internal value of a cell might be
0.678261
, but the cell might be formatted to handle decimals as percentages with hundredths-place precision, and so the end user might see that cell represented as67.83%
. But if they were to use it in a formula, or modify its value, the underlying value of0.678261
is what would be used/modified
- Example: The internal value of a cell might be
I'm trying to figure out how to do the same with POI.
Meaning, I would like to use POI's API to write an internal value to a cell, but then configure that cell to (visually) represent the value with a different formatting applied.
My two use cases are:
- Representing a numeric/decimal as a valid price (e.g. visually representing
203.9483495949
as$203.95
to the end users, or0.8375733
as$0.84
); and - Representing a numeric/decimal as a valid percentage (e.g. visually representing
0.009383484
as1.00%
to the end users, or0.53282
as53.28%
)
Currently I'm writing these values as follows:
BigDecimal validPrice = BigDecimal.valueOf(203.9483495949);
BigDecimal validPct = BigDecimal.valueOf(0.53282);
Row nextRow = sheet.createRow(rowNum);
nextRow.createCell(0).setCellValue(validPrice.doubleValue());
nextRow.createCell(1).setCellValue(validPct.doubleValue());
But when I write the data to an Excel file, I just see those same raw/internal values visualized (203.9483495949
and 0.53282
respectively) in the columns, and I have to manually set formatting on them after I open the files up. Instead, rather than forcing end users to apply this formatting manually, I'd like POI to apply the formatting in the code, so that when the files are opened, they are formatted as $203.95
and 53.28%
aleady.
Any idea as to how to do this?