使用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);
		}
	}  

以上代码参考自官方文档:http://poi.apache.org/spreadsheet/quick-guide.html#Validation


以上内容为原创,转载请注明出处:blog.csdn/net/levelmini

  • 8
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 6
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值