利用POI进行Excel的工作表(Sheet)复制时,如果复制的工作表(Sheet)较多(100个左右)或者Excel行数较多(5000+),会报告 workbook 的 cellstyle 创建不能超过4000 的错误.
The maximum number of cell styles was exceeded. You can define up to 4000 styles in a .xls workbook
(注:网上大多解决方案为把CreateCellStyle放在循环外面,但是对于Excel 的复制 是行不通的,为了最大限度的利用CellStyle,且控制在4000个之内.构造了一个缓存对象.来缓存创建的CellStyle,所有的CellStyle获取,先通过从缓存取,如果不存在再创建.代码如下)
public class CellStyleCache {
private static List<HSSFCellStyle> list = null;
public CellStyleCache(){
}
public static void Initialized(){
if(list==null||CacheManager.getCacheInfo("CellStyleCache").getValue()==null){
list = new ArrayList<HSSFCellStyle>();
CacheManager.putCacheInfo("CellStyleCache", list, 7200);
}
}
public static void addCellStyle(HSSFCellStyle style){
list.add(style);
}
public static HSSFCellStyle getCellStyle(HSSFCellStyle cellStyle){
for(HSSFCellStyle style : list){
if(style.getAlignment() == cellStyle.getAlignment()
//边框和边框颜色
&& style.getBorderBottom() == cellStyle.getBorderBottom()
&& style.getBorderLeft() == cellStyle.getBorderLeft()
&& style.getBorderRight() == cellStyle.getBorderRight()
&& style.getBorderTop() == cellStyle.getBorderTop()
&& style.getTopBorderColor() == cellStyle.getTopBorderColor()
&& style.getBottomBorderColor() == cellStyle.getBottomBorderColor()
&& style.getRightBorderColor() == cellStyle.getRightBorderColor()
&& style.getLeftBorderColor() == cellStyle.getLeftBorderColor()
//背景和前景
&& style.getFillBackgroundColor() == cellStyle.getFillBackgroundColor()
&& style.getFillForegroundColor() == cellStyle.getFillForegroundColor()
&& style.getHidden() == cellStyle.getHidden()
&& style.getVerticalAlignment() == cellStyle.getVerticalAlignment()){
return style;
}
}
addCellStyle(cellStyle);
return null;
}
}
因篇幅问题不能全部显示,请点此查看更多更全内容