import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class EasyPoiNumberValidation {
public static void main(String[] args) {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
Row row = sheet.createRow(0);
Cell cell = row.createCell(0);
// 设置单元格的值
cell.setCellValue("Only numbers allowed");
// 数据有效性设置
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createNumericConstraint(DataValidationConstraint.ValidationType.INTEGER,
DataValidationConstraint.OperatorType.BETWEEN,
"0",
"100");
CellRangeAddressList addressList = new CellRangeAddressList(0, 0, 0, 0); // 限定单元格A1
DataValidation dataValidation = helper.createValidation(constraint, addressList);
// 处理Excel的bug
if (dataValidation instanceof XSSFDataValidation) {
dataValidation.setSuppressDropDownArrow(true);
dataValidation.setShowErrorBox(true);
} else {
dataValidation.setSuppressDropDownArrow(false);
}
sheet.addValidationData(dataValidation);
// 写入文件
try (OutputStream out = new FileOutputStream("number_validation.xlsx")) {
workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
}
}
}