定义转换器
package com.haier.hibp.stock.util;
import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
/**
* LocalDateTime 时间格式转换器
*/
public final class LocalDateTimeConverter implements Converter<LocalDateTime> {
private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";
@Override
public Class<LocalDateTime> supportJavaTypeKey() {
return LocalDateTime.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception {
return LocalDateTime.parse(cellData.getStringValue(), DateTimeFormatter.ofPattern(getFormat(contentProperty)));
}
@Override
public WriteCellData<?> convertToExcelData(WriteConverterContext<LocalDateTime> context) throws Exception {
LocalDateTime value = context.getValue();
ExcelContentProperty contentProperty = context.getContentProperty();
return new WriteCellData<>(value.format(DateTimeFormatter.ofPattern(getFormat(contentProperty))));
}
private String getFormat(ExcelContentProperty contentProperty) {
if (contentProperty == null) {
return DEFAULT_FORMAT;
}
if (contentProperty.getDateTimeFormatProperty() == null) {
return DEFAULT_FORMAT;
}
return contentProperty.getDateTimeFormatProperty().getFormat();
}
}
使用转换器
ExcelWriter excelWriter = EasyExcelFactory.write(httpServletResponse.getOutputStream())
.build();
WriteSheet writeSheet = EasyExcelFactory.writerSheet(1, sheetName).head(clazz)
.registerConverter(new LongStringConverter())
.registerConverter(new LocalDateTimeConverter())
.registerWriteHandler(new AutoColumnWidthStrategy()).build();
excelWriter.write(data, writeSheet);
标签:return,contentProperty,格式,easyExcel,excel,alibaba,import,转换器,com
From: https://www.cnblogs.com/shareToAll/p/17617443.html