1. 复现 :使用POI导出带下拉框的excel文件,如果下拉框内容过多,下拉框变为了空
2. 解决思路 : 导出时创建隐藏的sheet,下拉框的取值从隐藏的sheet中获取,下拉框显示正常
3. 记录:因为网上的一些代码用的都不是SXSSFSheet创建 所以拿过来都需要改,所以我把改好的代码贴上来,大家就不用修改了
4.代码:
调用:
int sheetIndex = 1;
setLongHSSFValidation(workbook,textLine1,sheet,1,size,i,sheetIndex++);//下拉框1
setLongHSSFValidation(workbook,textLine2,sheet,1,size,i,sheetIndex++);//下拉框2
/**
* 解决下拉框过长不显示问题
* @param workbook
* @param deptList 下拉数据数组
* @param sheet
* @param firstRow 开始行
* @param endRow 结束行
* @param cellNum 下拉框所在的列
* @param sheetIndex 隐藏sheet名称
*/
public static void setLongHSSFValidation(SXSSFWorkbook workbook,String[] deptList ,SXSSFSheet sheet ,int firstRow, int endRow, int cellNum,int sheetIndex) {
String hiddenName = "hidden"+cellNum;
//1.创建隐藏的sheet页。 起个名字吧!叫"hidden"!
SXSSFSheet hidden = workbook.createSheet(hiddenName);
//2.循环赋值(为了防止下拉框的行数与隐藏域的行数相对应,将隐藏域加到结束行之后)
for (int i = 0, length = deptList.length; i < length; i++) {
hidden.createRow(endRow + i).createCell(cellNum).setCellValue(deptList[i]);
}
Name category1Name = workbook.createName();
category1Name.setNameName(hiddenName);
//3 A1:A代表隐藏域创建第N列createCell(N)时。以A1列开始A行数据获取下拉数组
category1Name.setRefersToFormula(hiddenName + "!A1:A" + (deptList.length + endRow));
//
DataValidationHelper helper = sheet.getDataValidationHelper();
DataValidationConstraint constraint = helper.createFormulaListConstraint(hiddenName);
CellRangeAddressList addressList = new CellRangeAddressList(1, endRow, cellNum, cellNum);
DataValidation dataValidation = helper.createValidation(constraint, addressList);
if (dataValidation instanceof XSSFDataValidation) {
// 数据校验
dataValidation.setSuppressDropDownArrow(true);
dataValidation.setShowErrorBox(true);
} else {
dataValidation.setSuppressDropDownArrow(false);
}
// 作用在目标sheet上
sheet.addValidationData(dataValidation);
// 设置hiddenSheet隐藏
workbook.setSheetHidden(sheetIndex, true);
}
5.这是一般的下拉框代码,数据量少的时候可以用
/** 有下拉框不显示的问题
* 设置excel下拉框
* @param sheet
* @param textlist 下拉数据列表
* @param firstRow
* @param endRow
* @param firstCol
* @param endCol
* @return
*/
public static SXSSFSheet setHSSFValidation(SXSSFSheet sheet,
String[] textlist, int firstRow, int endRow, int firstCol,
int endCol) {
// 设置数据有效性加载在哪个单元格上,四个参数分别是:起始行、终止行、起始列、终止列
CellRangeAddressList regions = new CellRangeAddressList(firstRow,
endRow, firstCol, endCol);
// 数据有效性对象
DataValidationHelper dataValidationHelper = sheet.getDataValidationHelper();
DataValidationConstraint createExplicitListConstraint = dataValidationHelper.createExplicitListConstraint(textlist);
DataValidation createValidation = dataValidationHelper.createValidation(createExplicitListConstraint, regions);
if (createValidation instanceof XSSFDataValidation) {
createValidation.setSuppressDropDownArrow(true);
createValidation.setShowErrorBox(true);
} else {
createValidation.setSuppressDropDownArrow(false);
}
sheet.addValidationData(createValidation);
return sheet;
}