Java导出excel下拉框大于255问题解决
问题描述:下载导入模板excel中有下拉框,内容过多,报错 String literals in formulas can’t be bigger than 255 characters ASCII 解决方法:
// wk:工作薄,sheepPro:导出主表,nameList:数据
private void initSecondIndustryData(Workbook wk,
HSSFSheet sheetPro,
List<String> nameList) {
// 创建名称管理器
Name namedCell = wk.createName();
namedCell.setNameName("name");
// 引用列,industry为上面创建的一张隐藏的sheet表,$A$2:$A$n,是此表中存放的数据
namedCell.setRefersToFormula("industry!$A$2:$A$" + nameList.size());
// 验证约束
DVConstraint industryPrimaryConstraint = DVConstraint.createFormulaListConstraint("name");
// 下拉框范围
CellRangeAddressList industryPrimaryRangeAddressList = new CellRangeAddressList(
1, // 第一行
INIT_MAX_ROW_NUM, // 最后一行, 对前10000条数据增加数据序列
NAME_NUM, // 下拉框所在列
NAME_NUM// 下拉框所在列
);
// 增加数据校验
DataValidation primaryDataValidation = new HSSFDataValidation(industryPrimaryRangeAddressList, industryPrimaryConstraint);
primaryDataValidation.createErrorBox("error", "请选择正确的行业!");
sheetPro.addValidationData(primaryDataValidation);
// firstList 第一个下拉框,secondList,通过firstList所选内容关联的第二个下拉框
// industryMap 自定义map,key:firstList内容,value:secondList
(String key : firstList ) {
List<String> secondList= industryMap.get(key);
Row row = sheet.createRow(0);
// 第一列放firstList数据;
row.createCell(0).setCellValue(key);
// 后面列存放secondList数据
for (int index = 0; index < secondList.size(); ++index) {
row.createCell(index + 1).setCellValue(secondList.get(index));
}
// 添加名称管理器,用作级联关联
String range = ExcelFileTemplateUtils.getRange(1, rowId, secondList.size());
Name name = book.createName();
name.setNameName(key);
name.setRefersToFormula("industry!" + range);
}
/**
* 计算formula
*
* @param offset 偏移量,如果给0,表示从A列开始,1,就是从B列
* @param rowId 第几行
* @param colCount 一共多少列
* @return 如果给入参 1,1,10. 表示从B1-K1。最终返回 $B$1:$K$1
*/
public static String getRange(int offset, int rowId, int colCount) {
char start = (char) (A + offset);
if (colCount <= 25) {
char end = (char) (start + colCount - 1);
return "$" + start + "$" + rowId + ":$" + end + "$" + rowId;
} else {
char endPrefix = A;
char endSuffix = A;
if ((colCount - 25) / 26 == 0 || colCount == 51) {
// 26-51之间,包括边界(仅两次字母表计算)
if ((colCount - 25) % 26 == 0) {
// 边界值
endSuffix = (char) (A + 25);
} else {
endSuffix = (char) (A + (colCount - 25) % 26 - 1);
}
} else {
// 51以上
if ((colCount - 25) % 26 == 0) {
endSuffix = (char) (A + 25);
endPrefix = (char) (endPrefix + (colCount - 25) / 26 - 1);
} else {
endSuffix = (char) (A + (colCount - 25) % 26 - 1);
endPrefix = (char) (endPrefix + (colCount - 25) / 26);
}
}
return "$" + start + "$" + rowId + ":$" + endPrefix + endSuffix + "$" + rowId;
}
}
名称管理器: 在office中,创建名称管理器不能以C开头。在WPS中可以
