本文共 1907 字,大约阅读时间需要 6 分钟。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | 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(); |
转载地址:http://vafbm.baihongyu.com/