alibaba / easyexcel

快速、简洁、解决大文件内存溢出的java处理Excel工具
https://easyexcel.opensource.alibaba.com
Apache License 2.0
32.69k stars 7.58k forks source link

CellStyle设置主动换行后,变成表头样式,单元格不生效 #3837

Open jakesang opened 5 months ago

jakesang commented 5 months ago

异常代码

@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
                              Head head,
                              Integer relativeRowIndex, Boolean isHead) {
    boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
    if (!needSetWidth) {
        return;
    }
    Map<Integer, Integer> maxColumnWidthMap = cache.get(writeSheetHolder.getSheetNo());
    if (maxColumnWidthMap == null) {
        maxColumnWidthMap = new HashMap<Integer, Integer>(16);
        cache.put(writeSheetHolder.getSheetNo(), maxColumnWidthMap);
    }
    Integer columnWidth = dataLength(cellDataList, cell, isHead);
    if (columnWidth < 0) {
        return;
    }
    if (columnWidth > MAX_COLUMN_WIDTH) {
        columnWidth = MAX_COLUMN_WIDTH;
        CellStyle cellStyle = cell.getCellStyle();
        if (cellStyle != null) {
            cellStyle.setWrapText(true);
        }
    }
    Integer maxColumnWidth = maxColumnWidthMap.get(cell.getColumnIndex());
    if (maxColumnWidth == null || columnWidth > maxColumnWidth) {
        maxColumnWidthMap.put(cell.getColumnIndex(), columnWidth);
        writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
    }
}

问题描述

1、这段代码是重写了LongestMatchColumnWidthStyleStrategy方法 2、为了自定义最大宽度,且当达到最大宽度时,单元格设置自动换行 3、debug调试过,确定到了具体的cell是执行了cellStyle.setWrapText(true); 4、实际下载的excel中变成表头有自动换行,目标单元格没有

mmmwanmmm commented 3 weeks ago

public class WrapTextWriteHandler extends AbstractCellWriteHandler {

private CellStyle cellStyle;

@Override
public void afterCellDispose(CellWriteHandlerContext context) {
    Cell cell = context.getCell();
    if (BooleanUtils.isNotTrue(context.getHead())) {
        Workbook workbook = context.getWriteWorkbookHolder().getWorkbook();
        CellStyle cellStyle = getCellStyle(workbook);
        cell.setCellStyle(cellStyle);
        context.getFirstCellData().setWriteCellStyle(null);
    }
}

public CellStyle getCellStyle(Workbook workbook) {
    if (cellStyle == null) {
        cellStyle = workbook.createCellStyle();
        cellStyle.setWrapText(true);
    }
    return cellStyle;
}

}