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)都无效