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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM