问题描述:
在使用EasyExcel导出Excel的过程中出现了如下异常:
IllegalArgumentException: The maximum length of cell contents (text) is 32,767 characters
分析:
在方法org.apache.poi.xssf.streaming.SXSSFCell#setCellValue(java.lang.String) 中:
public void setCellValue(String value) {
if (value != null) {
this.ensureTypeOrFormulaType(CellType.STRING);
//此处判断单元格中值的大小是否大于EXCEL2007.getMaxTextLength()
if (value.length() > SpreadsheetVersion.EXCEL2007.getMaxTextLength()) {
throw new IllegalArgumentException("The maximum length of cell contents (text) is 32,767 characters");
}
if (this._value.getType() == CellType.FORMULA) {
if (this._value instanceof SXSSFCell.NumericFormulaValue) {
((SXSSFCell.NumericFormulaValue)this._value).setPreEvaluatedValue(Double.parseDouble(value));
} else {
((SXSSFCell.StringFormulaValue)this._value).setPreEvaluatedValue(value);
}
} else {
((SXSSFCell.PlainStringValue)this._value).setValue(value);
}
} else {
this.setCellType(CellType.BLANK);
}
}
我们在来看看EXCEL2007.getMaxTextLength()的大小是多少:
问题解决:
方法一:
在自己的项目文件夹下创建org.apache.poi.ss.SpreadsheetVersion 类,复制poi中的该类源码,excel2007中的最后一个值改为int类型最大值。重试导出问题解决。
方法二:
利用反射强制将EXCEL2007中的_maxTextLength属性值修改为Integer.MAX_VALUE
public static void resetCellMaxTextLength() {
SpreadsheetVersion excel2007 = SpreadsheetVersion.EXCEL2007;
if (Integer.MAX_VALUE != excel2007.getMaxTextLength()) {
Field field;
try {
field = excel2007.getClass().getDeclaredField("_maxTextLength");
field.setAccessible(true);
field.set(excel2007,Integer.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
在EeayExcel调用之前执行:
问题解决。