[alibaba/easyexcel]如何给动态数据设置单元格格式为数值类型呢?(由于是动态数据就没有使用实体类注解的方式)

2023-12-17 65 views
4

EasyExcel.write(os) .registerWriteHandler(new AutoHeadColumnWidthStyleStrategy()) .autoCloseStream(Boolean.TRUE) .head(generateRoasExcelHeadTable(sspReportResponse)).sheet("ROAS Report") .doWrite(generateRoasExcelData(sspReportResponse));

`public class AutoHeadColumnWidthStyleStrategy extends AbstractColumnWidthStyleStrategy { private static final int MAX_COLUMN_WIDTH = 255;

private final Map<Integer, Map<Integer, Integer>> cache = MapUtils.newHashMapWithExpectedSize(8);

@Override
protected void setColumnWidth(WriteSheetHolder writeSheetHolder, List<WriteCellData<?>> cellDataList, Cell cell,
                              Head head, Integer relativeRowIndex, Boolean isHead) {
    if (isHead && cell.getRowIndex() != 0) {
        int columnWidth = cell.getStringCellValue().getBytes().length;
        if (columnWidth > MAX_COLUMN_WIDTH) {
            columnWidth = MAX_COLUMN_WIDTH;
        } else {
            columnWidth = columnWidth + 3;
        }
        writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);

    }
}

@Override
public void afterCellCreate(CellWriteHandlerContext context) {
    Cell cell = context.getCell();
    if(cell.getRowIndex()!=0){
        if (cell.getStringCellValue().matches("-?[0-9]+.?[0-9]*")) {
            WriteWorkbookHolder writeWorkbookHolder = context.getWriteWorkbookHolder();
            Workbook workbook = writeWorkbookHolder.getWorkbook();
            CellStyle cellStyle = workbook.createCellStyle();
            cellStyle.setDataFormat(HSSFDataFormat.getBuiltinFormat("0.00"));
            cell.setCellStyle(cellStyle);
            //cell.setCellType(CellType.NUMERIC);
        }
    }
}

/ @Override public void afterCellDispose(CellWriteHandlerContext context) { Cell cell = context.getCell(); if (cell.getStringCellValue().matches("-?[0-9]+.?[0-9]")) { cell.setCellType(CellType.NUMERIC); } }*/

private Integer dataLength(List<WriteCellData<?>> cellDataList, Cell cell, Boolean isHead) {
    if (isHead) {
        return cell.getStringCellValue().getBytes().length;
    }
    WriteCellData<?> cellData = cellDataList.get(0);
    CellDataTypeEnum type = cellData.getType();
    if (type == null) {
        return -1;
    }
    switch (type) {
        case STRING:
            return cellData.getStringValue().getBytes().length;
        case BOOLEAN:
            return cellData.getBooleanValue().toString().getBytes().length;
        case NUMBER:
            return cellData.getNumberValue().toString().getBytes().length;
        default:
            return -1;
    }
}

}`

这里的cell.setCellType(CellType.NUMERIC)以及cell.setCellStyle(cellStyle)都无效

回答

1

image

3

这是导出之后的格式 非数值类型

2

目前已经找到办法解决了 自定义一个转换器 将string转为number格式

8

麻烦问下,转换器是指拦截器吗?,可以给截一下“转换器”内块儿的代码吗

7

奥奥,说的是CellWriteHandler 吗

3

能告知一下是怎么解决的吗?目前我也遇到了同样的问题