欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-13 12:59:15
...

1.导入POI依赖

<!-- HSSF .xls -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.1.1</version>
</dependency>
<!-- XSSF .xlsx -->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.1.1</version>
</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"));
}