package cn.iocoder.yudao.framework.excel.core.handler;
|
|
import cn.idev.excel.write.handler.CellWriteHandler;
|
import cn.idev.excel.write.handler.context.CellWriteHandlerContext;
|
import org.apache.poi.ss.usermodel.Cell;
|
import org.apache.poi.ss.usermodel.CellType;
|
|
import java.time.LocalDate;
|
import java.time.LocalDateTime;
|
import java.time.format.DateTimeFormatter;
|
|
/**
|
* 把日期单元格强制写成纯文本的处理器
|
*
|
* <p>背景:FastExcel 在写出时,即使注册了字符串转换器,日期字段仍可能被内置的
|
* Number 转换器接管,最终在 Excel 里显示为 46023.0 这类序列号,使用者看不懂。</p>
|
*
|
* <p>本处理器在单元格写完后介入,把 LocalDate / LocalDateTime 类型的原始值
|
* 格式化为 yyyy-MM-dd / yyyy-MM-dd HH:mm:ss 并以文本写入。</p>
|
*
|
* <p>仅用于「下载导入模板」,不影响导入解析。</p>
|
*
|
* @author 超级管理员
|
*/
|
public class DateAsTextCellWriteHandler implements CellWriteHandler {
|
|
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
private static final DateTimeFormatter DATETIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
|
@Override
|
public void afterCellDispose(CellWriteHandlerContext context) {
|
// 只处理数据行,跳过表头
|
if (Boolean.TRUE.equals(context.getHead())) {
|
return;
|
}
|
Object value = context.getOriginalValue();
|
if (value == null) {
|
return;
|
}
|
String text = null;
|
if (value instanceof LocalDate localDate) {
|
text = localDate.format(DATE_FORMATTER);
|
} else if (value instanceof LocalDateTime localDateTime) {
|
text = localDateTime.format(DATETIME_FORMATTER);
|
} else if (value instanceof java.util.Date date) {
|
text = date.toInstant().atZone(java.time.ZoneId.systemDefault())
|
.toLocalDate().format(DATE_FORMATTER);
|
}
|
if (text == null) {
|
return;
|
}
|
Cell cell = context.getCell();
|
if (cell == null) {
|
return;
|
}
|
cell.setCellType(CellType.STRING);
|
cell.setCellValue(text);
|
}
|
|
}
|