xiaoyi
5 天以前 481d8165f26fc7e37f0e87f6444ac0340bb563a3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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);
    }
 
}