1. 复现 :使用POI导出带下拉框的excel文件,如果下拉框内容过多,下拉框变为了空
解决思路 : 导出时创建隐藏的sheet,下拉框的取值从隐藏的sheet中获取,下拉框显示正常
记录:因为网上的一些代码用的都不是SXSSFSheet创建 所以拿过来都需要改,所以我把改好的代码贴上来,大家就不用修改了
代码:
java
/**
* @description: 解决下拉框过长不显示问题
* @author: Johnny
* @param workbook
* @param sheet
* @param intArr (开始行,结束行,下拉框所在的列)
* @param deptList 下拉数据数组
* @return: void
**/
public static void setLongHSSFValidation(XSSFWorkbook workbook, XSSFSheet sheet,
Integer[] intArr, String[] deptList) {
int firstRow = intArr[0];
int endRow =intArr[1];
int cellNum =intArr[2];
String hiddenName = "hidden"+cellNum;
//1.创建隐藏的sheet页。
XSSFSheet 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(workbook.getSheetIndex(hiddenName), true);
}
- 这是一般的下拉框代码,数据量少的时候可以用
java
/**有下拉框不显示的问题
* 设置excel下拉框
* @param sheet
* @param textlist 下拉数据列表
* @param firstRow
* @param endRow
* @param firstCol
* @param endCol
* @return
*/
public static XSSFSheet setHSSFValidation(XSSFSheet 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;
}