将单元格限制为仅在Apache POI中的数值 [英] Limiting cells to only numeric values in Apache POI

查看:273
本文介绍了将单元格限制为仅在Apache POI中的数值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在使用Apache POI库来创建Excel工作表。

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

我们如何限制单元格只接受数值?是否有任何类仅限于Apache POI库中的数字?

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

谢谢

Rama Krishna

Thanks
Rama Krishna

推荐答案

也许,我应该问过我的问题,比如如何使用Apache POI在Excel中添加数据验证。

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.

我想这可以帮助别人。它对我有用。你需要小心Cell Range。

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);

这篇关于将单元格限制为仅在Apache POI中的数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆