使用POI為Excel新增資料有效性驗證
根據客戶要求需要新增資料有效性驗證。但是在查詢多方資料後發現,POI無法讀取到檔案中的有效性驗證,只能新增。無奈之下只能通過配置檔案的方式去添加了。
給Excel新增資料有效性的驗證,xls格式和xlsx格式不同,通過閱讀官方文件,總結出了以下方法
/**
* 新增資料有效性檢查.
* @param sheet 要新增此檢查的Sheet
* @param firstRow 開始行
* @param lastRow 結束行
* @param firstCol 開始列
* @param lastCol 結束列
* @param explicitListValues 有效性檢查的下拉列表
* @throws IllegalArgumentException 如果傳入的行或者列小於0(< 0)或者結束行/列比開始行/列小
*/
public static void setValidationData(Sheet sheet, int firstRow, int lastRow,
int firstCol, int lastCol,String[] explicitListValues) throws IllegalArgumentException{
if (firstRow < 0 || lastRow < 0 || firstCol < 0 || lastCol < 0 || lastRow < firstRow || lastCol < firstCol) {
throw new IllegalArgumentException(“Wrong Row or Column index : ” + firstRow+”:”+lastRow+”:”+firstCol+”:” +lastCol);
}
if (sheet instanceof XSSFSheet) {
XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper((XSSFSheet)sheet);
XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper
.createExplicitListConstraint(explicitListValues);
CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
XSSFDataValidation validation = (XSSFDataValidation) dvHelper.createValidation(dvConstraint, addressList);
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
} else if(sheet instanceof HSSFSheet){
CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(explicitListValues);
DataValidation validation = new HSSFDataValidation(addressList, dvConstraint);
validation.setSuppressDropDownArrow(true);
validation.setShowErrorBox(true);
sheet.addValidationData(validation);
}
}