XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(
                destinationSheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
                .createIntegerConstraint(OperatorType.EQUAL, "0", "10");
CellRangeAddressList addressList = new CellRangeAddressList(7,
                destinationSheet.getLastRowNum() + 1, 9, destinationSheet
                        .getRow(0).getLastCellNum());
XSSFDataValidation validation = (XSSFDataValidation) dvHelper
                .createValidation(dvConstraint, addressList);

validation.setErrorStyle(ErrorStyle.STOP);
validation.createErrorBox("Error", "Only numeric values are allowed");

destinationSheet.addValidationData(validation);


我使用了上面的代码,该代码不起作用,仍然可以接收单元格上的任何内容。如果我是对的,这条线是罪魁祸首。

XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
                    .createIntegerConstraint(OperatorType.EQUAL, "0", "10");


基本上,我希望“单元格”范围中的单元格仅接受0和10并限制字母字符。我也尝试了OperatorType.BETWEEN,但是没有运气。

这是我的参考。 Busy Developer

最佳答案

每当用户输入无效数据时,上面的代码都不会显示错误。

XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(
                destinationSheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
                .createIntegerConstraint(OperatorType.EQUAL, "0", "10");
CellRangeAddressList addressList = new CellRangeAddressList(7,
                destinationSheet.getLastRowNum() + 1, 9, destinationSheet
                        .getRow(0).getLastCellNum());
XSSFDataValidation validation = (XSSFDataValidation) dvHelper
                .createValidation(dvConstraint, addressList);

validation.setErrorStyle(ErrorStyle.STOP);
validation.createErrorBox("Error", "Only numeric values are allowed");
validation.setShowErrorBox(true); // The code is missing this line

destinationSheet.addValidationData(validation);


XSSF中的实现与HSSF不同,HSSF则不需要行validation.setShowErrorBox(true);来工作。我在先前的实现中使用了HSSF,其结果是未将showErrorBox设置为true。

10-07 21:03