本文介绍了将 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 ?
谢谢
拉玛克里希纳
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.
我想这可以帮助某人.它对我有用.您需要小心使用单元格范围.
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 中的单元格限制为仅数字值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!