看固定模板的设置格式是这样的 public class FourListExcelDto { @ContentStyle(dataFormat = 14) @DateTimeFormat("yyyy/M/dd") @ExcelProperty({"时间"}) private Date exportDate; } 但是非固定模板的是根据你来的数据来生成文件的这样就无法使用了。 用EasyExcel.write(outputStream).registerWriteHandler(xxx).doWrite(data)生成文件,我们可以自己实现一个registerWriteHandler,去格式化单元格。 新建Handler类,继承AbstractCellStyleStrategy public class ExcelCellStyleStrategy extends AbstractCellStyleStrategy { /** * 单元格格式列表(格式:GENERAL、CURRENCY_¥、CURRENCY_$、DATE、NUMERIC) */ private final List<String> cellDataTypes; /** * WorkBoot */ private Workbook workbook; /** * 构造方法,创建对象时传入需要定制的表头信息队列 */ public ExcelCellStyleStrategy(List<String> cellDataTypes) { this.cellDataTypes = cellDataTypes; } @Override protected void initCellStyle(Workbook workbook) { // 初始化信息时,保存Workbook对象,转换时需要使用 this.workbook = workbook; } @Override protected void setHeadCellStyle(Cell cell, Head head, Integer relativeRowIndex) { // 处理表头的 } @Override protected void setContentCellStyle(Cell cell, Head head, Integer relativeRowIndex) { CellStyle cellStyle = workbook.createCellStyle(); String cellValue = cell.getStringCellValue(); String dataTypes = cellDataTypes.get(head.getColumnIndex()); switch (dataTypes) { case "DATE": // 时间 if (StrUtil.isNotBlank(cellValue)) { DateTime dateTime = DateUtil.parseDateTime(cellValue); cell.setCellValue(DateUtil.format(dateTime, "yyyy/m/d h:mm")); cellStyle.setDataFormat((short) 164); } break; case "NUMERIC": // 数字 cell.setCellType(CellType.NUMERIC); // cellStyle.setDataFormat((short) 1); // 自定义格式 // 1 -> "0", 表示整数 // 2 -> "0.00", 表示浮点数 // 3 -> "#,##0", 表示三个数字加一个","格式的整数 // 4 -> "#,##0.00", 表示三个数字加一个","格式的浮点数 if (StrUtil.isBlank(cellValue)) { cell.setCellValue(""); } else { cell.setCellValue(Integer.parseInt(cellValue)); } break; default: if (dataTypes.startsWith("CURRENCY_")) { // 货币 String currency = dataTypes.substring(9); cell.setCellValue(StrUtil.format("{}{}", currency, StrUtil.isBlank(cellValue) ? "-" : cellValue)); cellStyle.setDataFormat((short) 42); } // 默认是通用类型,无需额外处理 } cell.setCellStyle(cellStyle); } } 主要看setContentCellStyle方法,创建ExcelCellStyleStrategy时需要把每一列的数据类型传递过来。 cellStyle.setDataFormat这个有意思,可以好好研究一下。 easypoi支持的自定义格式列表 BuiltinFormats类的_formats列表里的自定义格式才有效,否则就会使用文本格式。 记录数据类型就根据你实际情况来写了,下面时我这边的。根据业务来写的,别无脑跟! ![]()
设置效果 ![]()
货币 日期 唯重 关注 ———————————————— 版权声明:本文为CSDN博主「唯重」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 原文链接:https://blog.csdn.net/GMingZhou/article/details/124149506 |
|
来自: hncdman > 《easyexcel》