1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51
| /** * 单元格添加下拉菜单(不限制菜单可选项个数)<br/> * [注意:此方法会添加隐藏的sheet,可调用getDataSheetInDropMenuBook方法获取用户输入数据的未隐藏的sheet]<br/> * [待添加下拉菜单的单元格 -> 以下简称:目标单元格] * @param @param workbook * @param @param tarSheet 目标单元格所在的sheet * @param @param menuItems 下拉菜单可选项数组 * @param @param firstRow 第一个目标单元格所在的行号(从0开始) * @param @param lastRow 最后一个目标单元格所在的行(从0开始) * @param @param column 待添加下拉菜单的单元格所在的列(从0开始) String[] value = {"百世快递","京东","品骏","安能物流","天天","百世汇通","圆通","德邦快递","顺丰","百世快运","EMS","中通","德邦物流","百世-快递","韵达","百世物流","邮政包裹/平邮","申通","安能物流"};
*/ public static void addDropDownList(HSSFWorkbook workbook, HSSFSheet tarSheet, String[] menuItems, int firstRow, int lastRow, int column) throws Exception { if(null == workbook){ throw new Exception("workbook为null"); } if(null == tarSheet){ throw new Exception("待添加菜单的sheet为null"); }
//必须以字母开头,最长为31位 String hiddenSheetName = "a" + UUID.randomUUID().toString().replace("-", "").substring(1, 31); //excel中的"名称",用于标记隐藏sheet中的用作菜单下拉项的所有单元格 String formulaId = "form" + UUID.randomUUID().toString().replace("-", ""); HSSFSheet hiddenSheet = workbook.createSheet(hiddenSheetName);//用于存储 下拉菜单数据 //存储下拉菜单项的sheet页不显示 workbook.setSheetHidden(workbook.getSheetIndex(hiddenSheet), true);
HSSFRow row = null; HSSFCell cell = null; //隐藏sheet中添加菜单数据 for (int i = 0; i < menuItems.length; i++) { row = hiddenSheet.createRow(i); //隐藏表的数据列必须和添加下拉菜单的列序号相同,否则不能显示下拉菜单 cell = row.createCell(column); cell.setCellValue(menuItems[i]); }
HSSFName namedCell = workbook.createName();//创建"名称"标签,用于链接 namedCell.setNameName(formulaId); namedCell.setRefersToFormula(hiddenSheetName + "!A$1:A$" + menuItems.length); HSSFDataValidationHelper dvHelper = new HSSFDataValidationHelper(tarSheet); DataValidationConstraint dvConstraint = dvHelper.createFormulaListConstraint(formulaId);
CellRangeAddressList addressList = new CellRangeAddressList(firstRow, lastRow, column, column); HSSFDataValidation validation = (HSSFDataValidation)dvHelper.createValidation(dvConstraint, addressList);//添加菜单(将单元格与"名称"建立关联) tarSheet.addValidationData(validation); }
|