xiaoyi
6 天以前 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
package cn.iocoder.yudao.framework.excel.core.convert;
 
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;
 
/** Excel 是/否字段,拒绝无法识别的值,避免错误值被静默解析为否。 */
public class YesNoBooleanConverter implements Converter<Boolean> {
    @Override
    public Class<?> supportJavaTypeKey() { return Boolean.class; }
 
    @Override
    public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; }
 
    @Override
    public Boolean convertToJavaData(ReadCellData<?> data, ExcelContentProperty property, GlobalConfiguration config) {
        if (data.getType() == CellDataTypeEnum.BOOLEAN) return data.getBooleanValue();
        String value = data.getType() == CellDataTypeEnum.NUMBER && data.getNumberValue() != null
                ? data.getNumberValue().stripTrailingZeros().toPlainString() : data.getStringValue();
        if (value == null || value.trim().isEmpty()) return null;
        switch (value.trim().toLowerCase(java.util.Locale.ROOT)) {
            case "是": case "true": case "1": return true;
            case "否": case "false": case "0": return false;
            default: throw new IllegalArgumentException("是否需要来料检验仅支持是、否、1 或 0");
        }
    }
 
    @Override
    public WriteCellData<?> convertToExcelData(Boolean value, ExcelContentProperty property, GlobalConfiguration config) {
        return new WriteCellData<>(Boolean.TRUE.equals(value) ? "是" : "否");
    }
}