实现方法:

 //创建下拉框
    private static void creatDropDownList(Sheet taskInfoSheet, DataValidationHelper helper, String[] list,
                                          Integer firstRow, Integer lastRow, Integer firstCol, Integer lastCol) {
        //获取需要生成下拉框的格
        CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, firstCol, lastCol);
        //设置下拉框数据
        DataValidationConstraint constraint = helper.createExplicitListConstraint(list);
        DataValidation dataValidation = helper.createValidation(constraint, addressList);
        //处理Excel兼容性问题
        if (dataValidation instanceof XSSFDataValidation) {
            dataValidation.setSuppressDropDownArrow(true);
            dataValidation.setShowErrorBox(true);
        } else {
            dataValidation.setSuppressDropDownArrow(false);
        }
        taskInfoSheet.addValidationData(dataValidation);
    }

使用:

//创建HSSFWorkbook对象(excel的文档对象)
        XSSFWorkbook wb = new XSSFWorkbook();
        //建立新的sheet对象(excel的表单)
        XSSFSheet sheet = wb.createSheet("人员表");
		DataValidationHelper helper=sheet.getDataValidationHelper();
        String[] dlData = {"A","B","C","D","E","F","G","H"};
        //参数:表单对象,数据验证对象,下拉框数据,在第几行到第几行带有下拉框,第几列到第几列有下拉框
        creatDropDownList(sheet,helper,dlData,1,10,6,6);
Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐