Question

Using Apache POI to generate a document and i'm having a small problem with cell styles, currentlly i'm using:

CellStyle currencyCellStyle=workbook.createCellStyle();
currencyCellStyle.setDataFormat(format.getFormat("$#,##0.00"));

Which works totally fine for positive numbers, however I would like to assign a different style to negative cells automatically.

Question is is there any to set this up without having to check the individual cell values and assign a separate style to them?

Or alternatively is there any way to tell Apache POI to use the built in excel currency format with one of its negative options?

Was it helpful?

Solution

Found it, thanks me :D

CellStyle currencyCellStyle=workbook.createCellStyle();
currencyCellStyle.setDataFormat(format.getFormat("$#,##0.00;[Red]($#,##0.00)"));

OTHER TIPS

Why poi REFUSES to support the FIRST option in excel currency formatting is beyond me! enter image description here

I don't like using the DecimalFormat for currency because your end cell value becomes a non-numeric with the introduction of the currency symbol. While working for a major financial institution, I was tasked with resolving this formatting issue. The core idea of this change is, because POI refuses to be reasonable and have comprehensive support of Excel's native options, I will infiltrate their code and change their values at the core. The following is my WORKAROUND:

private static final String CURRENCY_FORMAT_OVERRIDE = "\"$\"#,##0.00_);-\"$\"#,##0.00";
private static final String CURRENCY_FORMAT_TARGET = "\"$\"#,##0.00_);(\"$\"#,##0.00)";    

static { // static class level initializer
    Field field = org.apache.poi.ss.usermodel.BuiltinFormats.class.getDeclaredField("_formats");            
    field.setAccessible(true);
    String[] _formats = (String[])field.get(new org.apache.poi.ss.usermodel.BuiltinFormats());
    for(int i = 0; i < _formats.length; ++i) {
        if(_formats[i].equals(CURRENCY_FORMAT_TARGET)) {
            _formats[i]=CURRENCY_FORMAT_OVERRIDE;
            System.out.println("TAKE THAT, POI!!!");
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top