poi 2003/2007 下拉框生成

POI 提供了很好的Excel 操作API,我这是用POI 3.8 主要核心jar包

poi-3.8-20120326.jar
poi-ooxml-3.8-20120326.jar



/**
* 生成下载模板,附带下拉框
* @param wb :工作簿
* @param datas:下拉框数据源
* @param selectCols:要生成下拉框的列
* @param sheetName:放置下拉框的sheet名称
* @param dataCol:放置下拉框数据的col字母
* @param dataColNum:放置下拉框数据的col 数字 0开始
* @param maxSelCols:生成下拉框的行数
* @return
*/
public static Workbook createSelectSheet(Workbook wb,
String[] datas,
int selectCols,
String sheetName,String dataCol,
int dataColNum,int maxSelCols){
DataValidationHelper dvHelper = null;
DataValidationConstraint dvConstraint = null;
DataValidation validation = null;
CellRangeAddressList addressList = null;
Sheet hidden = wb.createSheet(sheetName);//创建隐藏的sheet 用于放置下拉数据
wb.setSheetHidden(wb.getNumberOfSheets() -1, true);//专门放置数据源的sheet
Name namedCell = wb.createName();
namedCell.setNameName(sheetName);
// namedCell.setRefersToFormula(sheetName+"!$A$1:$A$10" + datas.length);
namedCell.setRefersToFormula(sheetName+"!$"+dataCol+"$1:$"+dataCol+"$"+datas.length);
Sheet sheet = wb.getSheetAt(0);
int sheetRows = maxSelCols;//当前sheet页的行数
Row row = null;
Cell cell = null;
if (wb instanceof HSSFWorkbook) {//xls
for (int i = 0, length = datas.length; i < length; i++) { //将数据源的数据放置到选定sheet的一列
row = (HSSFRow)hidden.createRow(i);
cell = (HSSFCell)row.createCell(dataColNum);
cell.setCellValue(datas[i]);
}
DVConstraint constraint = DVConstraint.createFormulaListConstraint(sheetName);
addressList = new CellRangeAddressList(1, sheetRows, selectCols, selectCols);
validation = new HSSFDataValidation(addressList, constraint);
sheet.addValidationData(validation);
validation.setShowErrorBox(false);// 取消弹出错误框
} else {//XLSX
for (int i = 0, length = datas.length; i < length; i++) {
row = (XSSFRow)hidden.createRow(i);
cell = (XSSFCell)row.createCell(dataColNum);
cell.setCellValue(datas[i]);
}
dvHelper = new XSSFDataValidationHelper((XSSFSheet) sheet);
dvConstraint = (XSSFDataValidationConstraint) dvHelper.createFormulaListConstraint(sheetName);
addressList = new CellRangeAddressList(1, sheetRows, selectCols, selectCols);
validation = (XSSFDataValidation) dvHelper.createValidation(
dvConstraint, addressList);
sheet.addValidationData(validation);//将下拉框放置到sheet
}
return wb;
}



调用此方法
wb = ExcelUtil.createSelectSheet(wb, list, 5,"hd","A",0,65534);//创建机构名称的下拉框

list 是数据源 string 数组

5 是 放置到模板的第6列

hd 是隐藏放置下拉框数据的sheet

A 是sheet中放置下拉数据的列

0表示第一列

65534 在模板中生成下拉框65534行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值