package cn.iocoder.yudao.framework.excel.core.convert;
|
|
import cn.hutool.core.util.StrUtil;
|
import cn.idev.excel.converters.Converter;
|
import cn.idev.excel.enums.CellDataTypeEnum;
|
import cn.idev.excel.metadata.GlobalConfiguration;
|
import cn.idev.excel.metadata.data.ReadCellData;
|
import cn.idev.excel.metadata.data.WriteCellData;
|
import cn.idev.excel.metadata.property.ExcelContentProperty;
|
|
import java.math.BigDecimal;
|
import java.time.LocalTime;
|
import java.time.format.DateTimeFormatter;
|
|
/**
|
* LocalTime 转换器
|
*
|
* FastExcel(cn.idev.excel)内置不支持 LocalTime,未指定 converter 时读写都会抛出
|
* Can not find Converter support class LocalTime。这里补上「HH:mm:ss 字符串」与
|
* 「Excel 时间数值(一天的占比)」两种写法的读写支持。
|
*
|
* @author 超级管理员
|
*/
|
public class LocalTimeConvert implements Converter<LocalTime> {
|
|
private static final DateTimeFormatter TIME_FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");
|
|
@Override
|
public Class<LocalTime> supportJavaTypeKey() {
|
return LocalTime.class;
|
}
|
|
@Override
|
public CellDataTypeEnum supportExcelTypeKey() {
|
return CellDataTypeEnum.STRING;
|
}
|
|
@Override
|
public LocalTime convertToJavaData(ReadCellData readCellData, ExcelContentProperty contentProperty,
|
GlobalConfiguration globalConfiguration) {
|
// 情况一:Excel 里填的是时间数值(一天的占比)
|
if (CellDataTypeEnum.NUMBER.equals(readCellData.getType())) {
|
BigDecimal numberValue = readCellData.getNumberValue();
|
if (numberValue == null) {
|
return null;
|
}
|
long secondOfDay = Math.round(numberValue.doubleValue() * 24 * 60 * 60) % (24 * 60 * 60);
|
return LocalTime.ofSecondOfDay(secondOfDay);
|
}
|
// 情况二:Excel 里填的是文本,如 8:30 / 08:30:00
|
String text = readCellData.getStringValue();
|
if (StrUtil.isBlank(text)) {
|
return null;
|
}
|
try {
|
String[] parts = text.trim().replace(':', ':').split(":");
|
int hour = Integer.parseInt(parts[0].trim());
|
int minute = parts.length > 1 ? Integer.parseInt(parts[1].trim()) : 0;
|
int second = parts.length > 2 ? Integer.parseInt(parts[2].trim()) : 0;
|
return LocalTime.of(hour, minute, second);
|
} catch (NumberFormatException | ArrayIndexOutOfBoundsException e) {
|
return null;
|
}
|
}
|
|
@Override
|
public WriteCellData<String> convertToExcelData(LocalTime value, ExcelContentProperty contentProperty,
|
GlobalConfiguration globalConfiguration) {
|
return new WriteCellData<>(value == null ? "" : value.format(TIME_FORMATTER));
|
}
|
|
}
|