Napstablook
Napstablook

Reputation: 614

Accept non negative float values in apache poi

I am creating an xlsx file using apache POI in java. I want a cell to have only non negative floating values with 2 decimal places at most. I am using createNumericConstraint for this, although in the file, it doesn't accept 0 as a value. (Find the code below). And I have no idea how to implement the 2 decimal places constraint on this as of yet.

Already got the answer for 2 decimal places. What I am stuck at is that it doesn't accept 0 as a value.

    DataValidationHelper helper = sheet.getDataValidationHelper();
    DataValidationConstraint constraint;
    DataValidation validation;
    constraint = helper.createNumericConstraint(XSSFDataValidationConstraint.ValidationType.DECIMAL,
            XSSFDataValidationConstraint.OperatorType.BETWEEN,
            String.valueOf(0),
            String.valueOf(Float.MAX_VALUE));

    CellRangeAddressList cellRangeAddressList = new CellRangeAddressList();

    cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(1, lastRowIndex, columns.get(SELLING_PRICE.getName()), columns.get(SELLING_PRICE.getName())));
    cellRangeAddressList.addCellRangeAddress(new CellRangeAddress(1, lastRowIndex, columns.get(MRP.getName()), columns.get(MRP.getName())));

    validation = helper.createValidation(constraint, cellRangeAddressList);
    validation.setSuppressDropDownArrow(false);
    validation.setShowErrorBox(true);
    sheet.addValidationData(validation);

Upvotes: 0

Views: 465

Answers (1)

LenglBoy
LenglBoy

Reputation: 1441

You can format all numbers using this line:

style.setDataFormat(workbook.createDataFormat().getFormat("0.00"));

The 0 does show up as required format every time. So some examples:

  • 0 -> 0.00
  • 1 -> 1.00
  • 1.5 -> 1.50
  • 99 -> 99.00
  • 137.7 -> 137.70

And last but not least the validation need to be changed from String.valueOf(0) to 0.00f so the format and correct datatype (float) is used. Otherwise there can be conversation/type-errors afterwards.

Upvotes: 2

Related Questions