首页 > 代码库 > Java通过POI为Excel添加数据验证
Java通过POI为Excel添加数据验证
String path = "d:\\success.xlsx"; String sheetName = "sheetlist"; XSSFWorkbook wb = null; XSSFSheet sheetlist = null; File inputFile = new File(path); if (inputFile.exists()) { wb = new XSSFWorkbook(new FileInputStream(path)); } else { wb = new XSSFWorkbook();// excel文件对象 } if (wb.getSheet(sheetName) == null) { sheetlist = wb.createSheet(sheetName);// 工作表对象 } else { sheetlist = wb.getSheet(sheetName);// 工作表对象 } DataValidationHelper helper = sheetlist.getDataValidationHelper(); List<XSSFDataValidation> dataValidations = sheetlist.getDataValidations(); for (XSSFDataValidation dv : dataValidations) { // 已有的验证 } // CellRangeAddressList dstAddrList = new CellRangeAddressList(0, 500, 0, 0);// 规则一单元格范围 String[] textlist = { "列表1", "列表2", "列表3", "列表4", "列表5" }; DataValidation dstDataValidation = helper.createValidation(helper.createExplicitListConstraint(textlist), dstAddrList); dstDataValidation.createPromptBox("提示头", "提示内容"); dstDataValidation.setShowErrorBox(true); dstDataValidation.setShowPromptBox(true); dstDataValidation.setEmptyCellAllowed(false); sheetlist.addValidationData(dstDataValidation); CellRangeAddressList dstAddrList2 = new CellRangeAddressList(0, 500, 1, 1);// 规则二单元格范围 DataValidationConstraint dvc = helper.createNumericConstraint(DVConstraint.ValidationType.INTEGER, DVConstraint.OperatorType.BETWEEN, "0", "9999999999"); DataValidation dstDataValidation2 = helper.createValidation(dvc, dstAddrList2); dstDataValidation2.createErrorBox("填错输啦!", "只能填那个啥啥啥"); dstDataValidation2.setEmptyCellAllowed(false); dstDataValidation2.setShowErrorBox(true); sheetlist.addValidationData(dstDataValidation2); FileOutputStream out = new FileOutputStream(path); wb.write(out); out.close();
Java通过POI为Excel添加数据验证
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。