Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all articles
Browse latest Browse all 88835

Applying price and percentage formatting in Apache POI

$
0
0

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 as 67.83%. But if they were to use it in a formula, or modify its value, the underlying value of 0.678261 is what would be used/modified

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:

  1. Representing a numeric/decimal as a valid price (e.g. visually representing 203.9483495949 as $203.95 to the end users, or 0.8375733 as $0.84); and
  2. Representing a numeric/decimal as a valid percentage (e.g. visually representing 0.009383484 as 1.00% to the end users, or 0.53282 as 53.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?


Viewing all articles
Browse latest Browse all 88835

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>