Apache poi给excel单元格添加下拉框或数据验证

系列文章目录

一、Java使用Apache POI导出excel
二、Apache POI 操作Excel常用方法
三、Apache poi 拆分单元格并赋值
四、使用easypoi模板方法导出excel
五、Apache poi给excel单元格添加下拉框或数据验证


文章目录

  • 系列文章目录
  • 一、效果展示
    • 在这里插入图片描述
  • 二、实现方法


一、效果展示

Apache poi给excel单元格添加下拉框或数据验证_第1张图片

二、实现方法

方法一

String[] values = {"参数1", "参数2", "参数3"};  // 长度不能超过255 否则会报错
setDropDownBox(sheet, values, 1, 100, 0, 0);

private static void setDropDownBox(
                    XSSFSheet sheet,   // 指定sheet页
					String[] values,   // 下拉框的值
					Integer firstRow,  // 起始行号
					Integer lastRow,   // 终止行号
					Integer firstCol,  // 起始列号
					Integer lastCol    // 终止列号
	) {
    XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
    XSSFDataValidationConstraint dvConstraint = (XSSFDataValidationConstraint) dvHelper.createExplicitListConstraint(values);
    CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
    DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
    //这两行设置单元格只能是列表中的内容,否则报错
    validation.setSuppressDropDownArrow(true);
    validation.setShowErrorBox(true);
    sheet.addValidationData(validation);
}

方法二

String strFormula = "部门列表!$A$1:$A$10";
setDropDownBoxString(sheet, strFormula, 1, 100, 1, 1);
        
private static void setDropDownBoxString(
		                    XSSFSheet sheet,   // 指定sheet页
							String values,     // 下拉框的值
							Integer firstRow,  // 起始行号
							Integer lastRow,   // 终止行号
							Integer firstCol,  // 起始列号
							Integer lastCol    // 终止列号
	) {
    XSSFDataValidationHelper dvHelper = new XSSFDataValidationHelper(sheet);
    XSSFDataValidationConstraint dvConstraint = new XSSFDataValidationConstraint(DataValidationConstraint.ValidationType.LIST,values);
    CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
    DataValidation validation = dvHelper.createValidation(dvConstraint, addressList);
    //这两行设置单元格只能是列表中的内容,否则报错
    validation.setSuppressDropDownArrow(true);
    validation.setShowErrorBox(true);
    sheet.addValidationData(validation);
}

你可能感兴趣的:(报表导出,excel,apache,java)