Limiting cells to only numeric values in Apache POI

烂漫一生 提交于 2019-12-07 18:42:20

问题


We are using Apache POI library to create the excel sheets.

How can we restrict the cells to accept only numeric values ? Is there any class that restricts to only numbers in Apache POI library ?

Thanks
Rama Krishna


回答1:


Perhaps, I should have asked my question like how to add Data Validation in Excel using Apache POI.

But here is the code to do so.

I guess this can help someone. It worked for me. You need to be careful with Cell Range.

XSSFWorkbook wb = new XSSFWorkbook(); 
XSSFSheet sheet = wb.createSheet("SomeSheet");

Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
XSSFDataValidationHelper dvHelper = new SSFDataValidationHelper(sheet);

XSSFDataValidationConstraint dvConstraint = 
    (XSSFDataValidationConstraint)
    dvHelper.createNumericConstraint(
        XSSFDataValidationConstraint.ValidationType.DECIMAL,
        XSSFDataValidationConstraint.OperatorType.BETWEEN,
        String.valueOf(Float.MIN_VALUE),
        String.valueOf(Float.MAX_VALUE)
    );

// Cell range is important here. 
CellRangeAddressList addressList = new CellRangeAddressList(
        0, 2, 1, 3);
// 0 - starting row, 2 - ending row
// 1 - starting col, 3 - ending col

XSSFDataValidation validation =(XSSFDataValidation)dvHelper.createValidation(
        dvConstraint, addressList);
validation.setSuppressDropDownArrow(false);
validation.setShowErrorBox(true);

CellStyle style = wb.createCellStyle();
style.setAlignment(CellStyle.ALIGN_LEFT);
cell.setCellStyle(style);

sheet.addValidationData(validation);

cell.setCellValue(20);


来源:https://stackoverflow.com/questions/37660522/limiting-cells-to-only-numeric-values-in-apache-poi

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!