poi导出excel设置单元格值的范围,下拉框选择

原创
2017/01/13 22:20
阅读数 1.8K

在做poi导出excel文件时,需要限定某个单元格值的范围,下拉可选

 

private void addValidate2Cell(Sheet sheet, int firstRow, int lastRow, int firstCol, int lastCol,HashMap<String, String> deviceCategryMap) {
		//值的范围为空,则不添加校验
		if(deviceCategryMap == null || deviceCategryMap.isEmpty()) 
			return;
		
		try {
			Collection<String> collection = deviceCategryMap.values();
			String[] category = new String[collection.size()];
			collection.toArray(category);
			if(sheet instanceof HSSFSheet){
				CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
				DVConstraint dvConstraint = DVConstraint.createExplicitListConstraint(category);
				DataValidation dataValidation = new HSSFDataValidation(addressList, dvConstraint);
				dataValidation.setSuppressDropDownArrow(false); //03默认false
				sheet.addValidationData(dataValidation);
			}else if(sheet instanceof XSSFSheet){
				XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
				XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint)dvHelper.createExplicitListConstraint(category);
				CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
				XSSFDataValidation validation = (XSSFDataValidation)dvHelper.createValidation(dvConstraint, addressList);
				validation.setShowErrorBox(true);
				validation.setSuppressDropDownArrow(true); //07默认true
				sheet.addValidationData(validation); 
			}
		} catch (Exception e) {
			//log.error("下拉框的选项过多导致出错:java.lang.IllegalArgumentException:String literals in formulas can't be bigger than 255 characters ASCII");
            e.printStackTrace();
		}

可查看官网文档,非常详细!

展开阅读全文
打赏
0
1 收藏
分享
加载中
更多评论
打赏
0 评论
1 收藏
0
分享
返回顶部
顶部