一、數據驗證概述
推薦以下操作在2007之后操作
1.1、查看excel的數據驗證
1、進入
2、設置規則
通過驗證條件允許,可以看到是每個單元格默認只成立一種條件
1.2、POI代碼開發-數據驗證
1.2.1、兩個數之間
public void excelRuleNumberBetween(Sheet sheet, int min, int max, int firstRow, int lastRow, int firstCol, int lastCol){ DataValidationHelper helper = sheet.getDataValidationHelper(); CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);//設置行列范圍 //設置數據 DataValidationConstraint constraint = helper.createIntegerConstraint(DataValidationConstraint.OperatorType.BETWEEN, String.valueOf(min),String.valueOf(max)); DataValidation dataValidation = helper.createValidation(constraint, addressList); dataValidation.createErrorBox("輸入值類型或大小有誤", String.format("請輸入%s~%s之間的數值",min,max)); //處理Excel兼容性問題 if(dataValidation instanceof XSSFDataValidation) { dataValidation.setSuppressDropDownArrow(true); dataValidation.setShowErrorBox(true); }else { dataValidation.setSuppressDropDownArrow(false); } sheet.addValidationData(dataValidation); }
1.2.2、選擇【序列】
public void excelRuleSelect(Sheet sheet, String[] rule, int firstRow, int lastRow, int firstCol, int lastCol) { DataValidationHelper helper = sheet.getDataValidationHelper(); CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol); DataValidationConstraint constraint = helper.createExplicitListConstraint(rule); DataValidation dataValidation = helper.createValidation(constraint, addressList); dataValidation.createErrorBox("輸入有誤", "請選擇下拉參數"); if (dataValidation instanceof XSSFDataValidation) { dataValidation.setSuppressDropDownArrow(true); dataValidation.setShowErrorBox(true); } else { dataValidation.setSuppressDropDownArrow(false); } sheet.addValidationData(dataValidation); }
1.2.3、列唯一
使用excel設置
POI設置
public void excelRuleUniqueue(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol) { Row row = sheet.getRow(0); Cell cell = row.getCell(firstCol); String r = ((XSSFCell) cell).getCTCell().getR(); r = r.substring(0, 1); DataValidationHelper helper = sheet.getDataValidationHelper(); CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol); //唯一 DataValidationConstraint constraint = helper.createCustomConstraint(MessageFormat.format("COUNTIF({0}:{0},{0}2)=1",r)); DataValidation dataValidation = helper.createValidation(constraint, addressList); dataValidation.createErrorBox("錯誤:", "賦值屬性列不允許重復"); dataValidation.setShowErrorBox(true); dataValidation.setEmptyCellAllowed(true); dataValidation.setSuppressDropDownArrow(true); dataValidation.setShowPromptBox(true); dataValidation.setErrorStyle(DataValidation.ErrorStyle.STOP); sheet.addValidationData(dataValidation); }
二、其他
2.1、列篩選
查看excel實現
POI代碼
Sheet sheetCreat = wbCreat.createSheet(sheet.getSheetName()); CellRangeAddress c = CellRangeAddress.valueOf(CELL_RANGE_ADDRESS); sheetCreat.setAutoFilter(c);