easypoi 报错You can define up to 64000styles in a .xlsx workbook

easypoi 导出数据为excel报错信息: The maximum number of cell styles was exceeded. You can define up to 64000styles in a .xlsx workbook 

解决方案自定义样式: 重复利用已有样式.

package com.hm.hny.common.utils.style;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.afterturn.easypoi.excel.export.styler.ExcelExportStylerDefaultImpl;
import org.apache.poi.ss.usermodel.*;
import org.springblade.core.tool.utils.Func;

public class ExcelExportNumberStyler extends ExcelExportStylerDefaultImpl {

    public CellStyle numberCellStyle;

    public ExcelExportNumberStyler(Workbook workbook) {
        super(workbook);
        createNumberCellStyler();//预生成样式
    }

    private void createNumberCellStyler() {
        //自定义样式不为空时,重复利用
        if(Func.isEmpty(numberCellStyle)){
            numberCellStyle = workbook.createCellStyle();
            numberCellStyle.setAlignment(HorizontalAlignment.CENTER);//水平居中
            numberCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);//垂直居中
            /*numberCellStyle.setDataFormat((short) BuiltinFormats.getBuiltinFormat("0.00"));//格式化
            numberCellStyle.setWrapText(true); //换行 */
        }
    }

    @Override
    public CellStyle getStyles(boolean noneStyler, ExcelExportEntity entity) {
        if (entity != null
            && 10==entity.getType()) {
            //数值类型用自定义样式
            return numberCellStyle;
        }
        return super.getStyles(noneStyler, entity);
    }

}

使用:

ExportParams params = new ExportParams("xx导出", "xx查询导出", ExcelType.XSSF);
params.setStyle(ExcelExportNumberStyler.class);//设置数字格式自定义导出

此问题导致原因是由于createCellStyle();

workbook.createCellStyle();

最终会到StyleTable#createCellStyle方法

/**
     * Create a cell style in this style table.
     * Note - End users probably want to call {@link XSSFWorkbook#createCellStyle()}
     * rather than working with the styles table directly.
     * @throws IllegalStateException if the maximum number of cell styles has been reached. 
     */
    public XSSFCellStyle createCellStyle() {
        if (getNumCellStyles() > MAXIMUM_STYLE_ID) {
            throw new IllegalStateException("The maximum number of Cell Styles was exceeded. " +
                      "You can define up to " + MAXIMUM_STYLE_ID + " style in a .xlsx Workbook");
        }

        int xfSize = styleXfs.size();
        CTXf xf = CTXf.Factory.newInstance();
        xf.setNumFmtId(0);
        xf.setFontId(0);
        xf.setFillId(0);
        xf.setBorderId(0);
        xf.setXfId(0);
        int indexXf = putCellXf(xf);
        return new XSSFCellStyle(indexXf - 1, xfSize - 1, this, theme);
    }
View Code
MAXIMUM_STYLE_ID = 64000
这个限制是有道理的,不然你创建了很多个CellStyle对象.

朋友们对easyPOi导出由于注解@Excel type = 10 导致样式没有重复利用的问题,有更好的办法,欢迎留言!
原文地址:https://www.cnblogs.com/yxgmagic/p/14182679.html