excel -> easyexcel java时间转换问题

https://blog.csdn.net/qq_20009015/article/details/85243033

导入日期的有3种方式:
1.excel文档日期列设置为文本类型,用LocalDateTimeConverter.class
2.类中日期变量类型改为Date, 加上@DateTimeFormat
3.excel日期字段是按一定规则生成的数字,自定义转换器将数字转为日期,参考https://blog.csdn.net/qq_20009015/article/details/85243033

LocalDateTime:

public class LocalDateTimeConverter implements Converter<LocalDateTime> {
    @Override
    public Class supportJavaTypeKey() {
        return LocalDateTime.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    @Override
    public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    @Override
    public CellData convertToExcelData(LocalDateTime value, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        return new CellData<>(value.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    }
}

如下

    @ExcelProperty(value = "创建时间", converter = LocalDateTimeConverter.class)
    private LocalDateTime createTime;

Date:

package com.alibaba.excel.annotation.format;

@java.lang.annotation.Target({java.lang.annotation.ElementType.FIELD})
@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.RUNTIME)
@java.lang.annotation.Inherited
public @interface DateTimeFormat {
    java.lang.String value() default "";

    boolean use1904windowing() default false;
}

如下

    @DateTimeFormat("yyyy-MM-dd HH:mm:ss")
    private Date createtime;

时间如果是yyyy-MM-dd格式,可以参考
https://stackoverflow.com/questions/42763103/convert-string-yyyy-mm-dd-to-localdatetime

当时间格式是NUMBER时,进行转换,由于EXCEL时间和时间戳时间的差异.
这里需要做一些调整

    @Override
    public LocalDateTime convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws Exception {
        BigDecimal numberValue = cellData.getNumberValue();
        System.out.println("numberValue:"+numberValue);
        long second = numberValue.multiply(new BigDecimal("86400")).longValue();
        System.out.println("second:"+second);
        Instant instant = Instant.ofEpochSecond(second-2209190400L);
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }

这个2209190400L数字是70年+2天+17天+8小时的秒数,也就是excel时间和localDateTime转换的时差

参考:
https://www.cmsky.com/why-computer-time-1970/
https://www.office68.com/excel/3720.html

posted @ 2020-12-24 09:32  ukyo--夜王  阅读(7901)  评论(0编辑  收藏  举报