Apache POI实现数据下拉框(HSSF和XSSF通用)

文章目录

    • 1.导入POI依赖
    • 2.代码实现

1.导入POI依赖


<dependency>
    <groupId>org.apache.poigroupId>
    <artifactId>poiartifactId>
    <version>4.1.1version>
dependency>

<dependency>
    <groupId>org.apache.poigroupId>
    <artifactId>poi-ooxmlartifactId>
    <version>4.1.1version>
dependency>

2.代码实现

public void test(){
	// Workbook wb = new HSSFWorkbook();
	Workbook wb = new XSSFWorkbook();
    Sheet sheet = wb.createSheet("sheet0");
    // 设置区域范围, 参数:firstRow,lastRow,firstCol,lastCol
    // 示例为第一个单元格
    CellRangeAddressList cellRangeAddressList = new CellRangeAddressList(0, 0, 0, 0);
    DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
    // 构造下拉框和数据
    DataValidationConstraint constraint = dataValidationHelper.createExplicitListConstraint(new String[]{"春", "夏", "秋", "冬"});
    // 绑定下拉框和区域
    DataValidation validation = dataValidationHelper.createValidation(constraint, cellRangeAddressList);
    // 为sheet添加验证
    sheet.addValidationData(validation);
    //wb.write(new FileOutputStream("D:\\test.xls"));
    wb.write(new FileOutputStream("D:\\test.xlsx"));
}

你可能感兴趣的:(POI)