repo
stringclasses
1k values
file_url
stringlengths
96
373
file_path
stringlengths
11
294
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
6 values
commit_sha
stringclasses
1k values
retrieved_at
stringdate
2026-01-04 14:45:56
2026-01-04 18:30:23
truncated
bool
2 classes
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/integer/IntegerNumberConverter.java
package com.alibaba.excel.converters.integer; 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 com.alibaba.excel.util.NumberUtils; /** * Integer and number converter * * @author Jiaju Zhuang */ public class IntegerNumberConverter implements Converter<Integer> { @Override public Class<?> supportJavaTypeKey() { return Integer.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.NUMBER; } @Override public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().intValue(); } @Override public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) { return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty()); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/integer/IntegerStringConverter.java
package com.alibaba.excel.converters.integer; import java.text.ParseException; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.NumberUtils; /** * Integer and string converter * * @author Jiaju Zhuang */ public class IntegerStringConverter implements Converter<Integer> { @Override public Class<?> supportJavaTypeKey() { return Integer.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseInteger(cellData.getStringValue(), contentProperty); } @Override public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/byteconverter/ByteStringConverter.java
package com.alibaba.excel.converters.byteconverter; import java.text.ParseException; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.NumberUtils; /** * Byte and string converter * * @author Jiaju Zhuang */ public class ByteStringConverter implements Converter<Byte> { @Override public Class<?> supportJavaTypeKey() { return Byte.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public Byte convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseByte(cellData.getStringValue(), contentProperty); } @Override public WriteCellData<?> convertToExcelData(Byte value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/byteconverter/ByteNumberConverter.java
package com.alibaba.excel.converters.byteconverter; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.NumberUtils; /** * Byte and number converter * * @author Jiaju Zhuang */ public class ByteNumberConverter implements Converter<Byte> { @Override public Class<?> supportJavaTypeKey() { return Byte.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.NUMBER; } @Override public Byte convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().byteValue(); } @Override public WriteCellData<?> convertToExcelData(Byte value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellData(value, contentProperty); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/byteconverter/ByteBooleanConverter.java
package com.alibaba.excel.converters.byteconverter; import com.alibaba.excel.converters.Converter; 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; /** * Byte and boolean converter * * @author Jiaju Zhuang */ public class ByteBooleanConverter implements Converter<Byte> { private static final Byte ONE = (byte)1; private static final Byte ZERO = (byte)0; @Override public Class<?> supportJavaTypeKey() { return Byte.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.BOOLEAN; } @Override public Byte convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; } return ZERO; } @Override public WriteCellData<?> convertToExcelData(Byte value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { return new WriteCellData<>(Boolean.TRUE); } return new WriteCellData<>(Boolean.FALSE); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/url/UrlImageConverter.java
package com.alibaba.excel.converters.url; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.IoUtils; /** * Url and image converter * * @author Jiaju Zhuang * @since 2.1.1 */ public class UrlImageConverter implements Converter<URL> { public static int urlConnectTimeout = 1000; public static int urlReadTimeout = 5000; @Override public Class<?> supportJavaTypeKey() { return URL.class; } @Override public WriteCellData<?> convertToExcelData(URL value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { InputStream inputStream = null; try { URLConnection urlConnection = value.openConnection(); urlConnection.setConnectTimeout(urlConnectTimeout); urlConnection.setReadTimeout(urlReadTimeout); inputStream = urlConnection.getInputStream(); byte[] bytes = IoUtils.toByteArray(inputStream); return new WriteCellData<>(bytes); } finally { if (inputStream != null) { inputStream.close(); } } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalBooleanConverter.java
package com.alibaba.excel.converters.bigdecimal; import java.math.BigDecimal; import com.alibaba.excel.converters.Converter; 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; /** * BigDecimal and boolean converter * * @author Jiaju Zhuang */ public class BigDecimalBooleanConverter implements Converter<BigDecimal> { @Override public Class<BigDecimal> supportJavaTypeKey() { return BigDecimal.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.BOOLEAN; } @Override public BigDecimal convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return BigDecimal.ONE; } return BigDecimal.ZERO; } @Override public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (BigDecimal.ONE.equals(value)) { return new WriteCellData<>(Boolean.TRUE); } return new WriteCellData<>(Boolean.FALSE); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalNumberConverter.java
package com.alibaba.excel.converters.bigdecimal; import java.math.BigDecimal; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.NumberUtils; /** * BigDecimal and number converter * * @author Jiaju Zhuang */ public class BigDecimalNumberConverter implements Converter<BigDecimal> { @Override public Class<BigDecimal> supportJavaTypeKey() { return BigDecimal.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.NUMBER; } @Override public BigDecimal convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue(); } @Override public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellData(value, contentProperty); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/bigdecimal/BigDecimalStringConverter.java
package com.alibaba.excel.converters.bigdecimal; import java.math.BigDecimal; import java.text.ParseException; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.NumberUtils; /** * BigDecimal and string converter * * @author Jiaju Zhuang */ public class BigDecimalStringConverter implements Converter<BigDecimal> { @Override public Class<BigDecimal> supportJavaTypeKey() { return BigDecimal.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public BigDecimal convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseBigDecimal(cellData.getStringValue(), contentProperty); } @Override public WriteCellData<?> convertToExcelData(BigDecimal value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/shortconverter/ShortBooleanConverter.java
package com.alibaba.excel.converters.shortconverter; import com.alibaba.excel.converters.Converter; 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; /** * Short and boolean converter * * @author Jiaju Zhuang */ public class ShortBooleanConverter implements Converter<Short> { private static final Short ONE = 1; private static final Short ZERO = 0; @Override public Class<Short> supportJavaTypeKey() { return Short.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.BOOLEAN; } @Override public Short convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; } return ZERO; } @Override public WriteCellData<?> convertToExcelData(Short value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { return new WriteCellData<>(Boolean.TRUE); } return new WriteCellData<>(Boolean.FALSE); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/shortconverter/ShortStringConverter.java
package com.alibaba.excel.converters.shortconverter; import java.text.ParseException; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.NumberUtils; /** * Short and string converter * * @author Jiaju Zhuang */ public class ShortStringConverter implements Converter<Short> { @Override public Class<?> supportJavaTypeKey() { return Short.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public Short convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseShort(cellData.getStringValue(), contentProperty); } @Override public WriteCellData<?> convertToExcelData(Short value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/shortconverter/ShortNumberConverter.java
package com.alibaba.excel.converters.shortconverter; 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 com.alibaba.excel.util.NumberUtils; /** * Short and number converter * * @author Jiaju Zhuang */ public class ShortNumberConverter implements Converter<Short> { @Override public Class<Short> supportJavaTypeKey() { return Short.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.NUMBER; } @Override public Short convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().shortValue(); } @Override public WriteCellData<?> convertToExcelData(WriteConverterContext<Short> context) { return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty()); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanStringConverter.java
package com.alibaba.excel.converters.booleanconverter; import com.alibaba.excel.converters.Converter; 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; /** * Boolean and string converter * * @author Jiaju Zhuang */ public class BooleanStringConverter implements Converter<Boolean> { @Override public Class<?> supportJavaTypeKey() { return Boolean.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public Boolean convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return Boolean.valueOf(cellData.getStringValue()); } @Override public WriteCellData<?> convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return new WriteCellData<>(value.toString()); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanNumberConverter.java
package com.alibaba.excel.converters.booleanconverter; import java.math.BigDecimal; import com.alibaba.excel.converters.Converter; 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; /** * Boolean and number converter * * @author Jiaju Zhuang */ public class BooleanNumberConverter implements Converter<Boolean> { @Override public Class<?> supportJavaTypeKey() { return Boolean.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.NUMBER; } @Override public Boolean convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (BigDecimal.ONE.compareTo(cellData.getNumberValue()) == 0) { return Boolean.TRUE; } return Boolean.FALSE; } @Override public WriteCellData<?> convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (value) { return new WriteCellData<>(BigDecimal.ONE); } return new WriteCellData<>(BigDecimal.ZERO); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/booleanconverter/BooleanBooleanConverter.java
package com.alibaba.excel.converters.booleanconverter; import com.alibaba.excel.converters.Converter; 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; /** * Boolean and boolean converter * * @author Jiaju Zhuang */ public class BooleanBooleanConverter implements Converter<Boolean> { @Override public Class<?> supportJavaTypeKey() { return Boolean.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.BOOLEAN; } @Override public Boolean convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getBooleanValue(); } @Override public WriteCellData<?> convertToExcelData(Boolean value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return new WriteCellData<>(value); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/floatconverter/FloatBooleanConverter.java
package com.alibaba.excel.converters.floatconverter; import com.alibaba.excel.converters.Converter; 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; /** * Float and boolean converter * * @author Jiaju Zhuang */ public class FloatBooleanConverter implements Converter<Float> { private static final Float ONE = (float)1.0; private static final Float ZERO = (float)0.0; @Override public Class<?> supportJavaTypeKey() { return Float.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.BOOLEAN; } @Override public Float convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; } return ZERO; } @Override public WriteCellData<?> convertToExcelData(Float value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { return new WriteCellData<>(Boolean.TRUE); } return new WriteCellData<>(Boolean.FALSE); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/floatconverter/FloatStringConverter.java
package com.alibaba.excel.converters.floatconverter; import java.text.ParseException; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.NumberUtils; /** * Float and string converter * * @author Jiaju Zhuang */ public class FloatStringConverter implements Converter<Float> { @Override public Class<?> supportJavaTypeKey() { return Float.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public Float convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseFloat(cellData.getStringValue(), contentProperty); } @Override public WriteCellData<?> convertToExcelData(Float value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/floatconverter/FloatNumberConverter.java
package com.alibaba.excel.converters.floatconverter; 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 com.alibaba.excel.util.NumberUtils; /** * Float and number converter * * @author Jiaju Zhuang */ public class FloatNumberConverter implements Converter<Float> { @Override public Class<?> supportJavaTypeKey() { return Float.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.NUMBER; } @Override public Float convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().floatValue(); } @Override public WriteCellData<?> convertToExcelData(WriteConverterContext<Float> context) { return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty()); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/longconverter/LongStringConverter.java
package com.alibaba.excel.converters.longconverter; import java.text.ParseException; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.NumberUtils; /** * Long and string converter * * @author Jiaju Zhuang */ public class LongStringConverter implements Converter<Long> { @Override public Class<Long> supportJavaTypeKey() { return Long.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { return NumberUtils.parseLong(cellData.getStringValue(), contentProperty); } @Override public WriteCellData<?> convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return NumberUtils.formatToCellDataString(value, contentProperty); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/longconverter/LongBooleanConverter.java
package com.alibaba.excel.converters.longconverter; import com.alibaba.excel.converters.Converter; 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; /** * Long and boolean converter * * @author Jiaju Zhuang */ public class LongBooleanConverter implements Converter<Long> { private static final Long ONE = 1L; private static final Long ZERO = 0L; @Override public Class<Long> supportJavaTypeKey() { return Long.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.BOOLEAN; } @Override public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (cellData.getBooleanValue()) { return ONE; } return ZERO; } @Override public WriteCellData<?> convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (ONE.equals(value)) { return new WriteCellData<>(Boolean.TRUE); } return new WriteCellData<>(Boolean.FALSE); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/longconverter/LongNumberConverter.java
package com.alibaba.excel.converters.longconverter; 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 com.alibaba.excel.util.NumberUtils; /** * Long and number converter * * @author Jiaju Zhuang */ public class LongNumberConverter implements Converter<Long> { @Override public Class<Long> supportJavaTypeKey() { return Long.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.NUMBER; } @Override public Long convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { return cellData.getNumberValue().longValue(); } @Override public WriteCellData<?> convertToExcelData(WriteConverterContext<Long> context) { return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty()); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/inputstream/InputStreamImageConverter.java
package com.alibaba.excel.converters.inputstream; import java.io.IOException; import java.io.InputStream; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.IoUtils; /** * File and image converter * * @author Jiaju Zhuang */ public class InputStreamImageConverter implements Converter<InputStream> { @Override public Class<?> supportJavaTypeKey() { return InputStream.class; } @Override public WriteCellData<?> convertToExcelData(InputStream value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException { return new WriteCellData<>(IoUtils.toByteArray(value)); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/localdatetime/LocalDateTimeNumberConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/localdatetime/LocalDateTimeNumberConverter.java
package com.alibaba.excel.converters.localdatetime; import java.math.BigDecimal; import java.time.LocalDateTime; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.DateUtils; import org.apache.poi.ss.usermodel.DateUtil; /** * LocalDateTime and number converter * * @author Jiaju Zhuang */ public class LocalDateTimeNumberConverter implements Converter<LocalDateTime> { @Override public Class<?> supportJavaTypeKey() { return LocalDateTime.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.NUMBER; } @Override public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { return DateUtils.getLocalDateTime(cellData.getNumberValue().doubleValue(), globalConfiguration.getUse1904windowing()); } else { return DateUtils.getLocalDateTime(cellData.getNumberValue().doubleValue(), contentProperty.getDateTimeFormatProperty().getUse1904windowing()); } } @Override public WriteCellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { return new WriteCellData<>( BigDecimal.valueOf(DateUtil.getExcelDate(value, globalConfiguration.getUse1904windowing()))); } else { return new WriteCellData<>(BigDecimal.valueOf( DateUtil.getExcelDate(value, contentProperty.getDateTimeFormatProperty().getUse1904windowing()))); } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/localdatetime/LocalDateTimeDateConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/localdatetime/LocalDateTimeDateConverter.java
package com.alibaba.excel.converters.localdatetime; import java.time.LocalDateTime; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.WorkBookUtil; /** * LocalDateTime and date converter * * @author Jiaju Zhuang */ public class LocalDateTimeDateConverter implements Converter<LocalDateTime> { @Override public Class<?> supportJavaTypeKey() { return LocalDateTime.class; } @Override public WriteCellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws Exception { WriteCellData<?> cellData = new WriteCellData<>(value); String format = null; if (contentProperty != null && contentProperty.getDateTimeFormatProperty() != null) { format = contentProperty.getDateTimeFormatProperty().getFormat(); } WorkBookUtil.fillDataFormat(cellData, format, DateUtils.defaultDateFormat); return cellData; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/converters/localdatetime/LocalDateTimeStringConverter.java
easyexcel-core/src/main/java/com/alibaba/excel/converters/localdatetime/LocalDateTimeStringConverter.java
package com.alibaba.excel.converters.localdatetime; import java.text.ParseException; import java.time.LocalDateTime; import com.alibaba.excel.converters.Converter; 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 com.alibaba.excel.util.DateUtils; /** * LocalDateTime and string converter * * @author Jiaju Zhuang */ public class LocalDateTimeStringConverter implements Converter<LocalDateTime> { @Override public Class<?> supportJavaTypeKey() { return LocalDateTime.class; } @Override public CellDataTypeEnum supportExcelTypeKey() { return CellDataTypeEnum.STRING; } @Override public LocalDateTime convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws ParseException { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { return DateUtils.parseLocalDateTime(cellData.getStringValue(), null, globalConfiguration.getLocale()); } else { return DateUtils.parseLocalDateTime(cellData.getStringValue(), contentProperty.getDateTimeFormatProperty().getFormat(), globalConfiguration.getLocale()); } } @Override public WriteCellData<?> convertToExcelData(LocalDateTime value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) { if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) { return new WriteCellData<>(DateUtils.format(value, null, globalConfiguration.getLocale())); } else { return new WriteCellData<>( DateUtils.format(value, contentProperty.getDateTimeFormatProperty().getFormat(), globalConfiguration.getLocale())); } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java
easyexcel-core/src/main/java/com/alibaba/excel/support/ExcelTypeEnum.java
package com.alibaba.excel.support; import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelCommonException; import com.alibaba.excel.read.metadata.ReadWorkbook; import com.alibaba.excel.util.StringUtils; import lombok.Getter; import org.apache.poi.util.IOUtils; /** * @author jipengfei */ @Getter public enum ExcelTypeEnum { /** * csv */ CSV(".csv", new byte[] {-27, -89, -109, -27}), /** * xls */ XLS(".xls", new byte[] {-48, -49, 17, -32, -95, -79, 26, -31}), /** * xlsx */ XLSX(".xlsx", new byte[] {80, 75, 3, 4}); final String value; final byte[] magic; ExcelTypeEnum(String value, byte[] magic) { this.value = value; this.magic = magic; } final static int MAX_PATTERN_LENGTH = 8; public static ExcelTypeEnum valueOf(ReadWorkbook readWorkbook) { ExcelTypeEnum excelType = readWorkbook.getExcelType(); if (excelType != null) { return excelType; } File file = readWorkbook.getFile(); InputStream inputStream = readWorkbook.getInputStream(); if (file == null && inputStream == null) { throw new ExcelAnalysisException("File and inputStream must be a non-null."); } try { if (file != null) { if (!file.exists()) { throw new ExcelAnalysisException("File " + file.getAbsolutePath() + " not exists."); } // If there is a password, use the FileMagic first if (!StringUtils.isEmpty(readWorkbook.getPassword())) { try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) { return recognitionExcelType(bufferedInputStream); } } // Use the name to determine the type String fileName = file.getName(); if (fileName.endsWith(XLSX.getValue())) { return XLSX; } else if (fileName.endsWith(XLS.getValue())) { return XLS; } else if (fileName.endsWith(CSV.getValue())) { return CSV; } if (StringUtils.isEmpty(readWorkbook.getPassword())) { try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) { return recognitionExcelType(bufferedInputStream); } } } if (!inputStream.markSupported()) { inputStream = new BufferedInputStream(inputStream); readWorkbook.setInputStream(inputStream); } return recognitionExcelType(inputStream); } catch (ExcelCommonException e) { throw e; } catch (Exception e) { throw new ExcelCommonException( "Convert excel format exception.You can try specifying the 'excelType' yourself", e); } } private static ExcelTypeEnum recognitionExcelType(InputStream inputStream) throws Exception { // Grab the first bytes of this stream byte[] data = IOUtils.peekFirstNBytes(inputStream, MAX_PATTERN_LENGTH); if (findMagic(XLSX.magic, data)) { return XLSX; } else if (findMagic(XLS.magic, data)) { return XLS; } // csv has no fixed prefix, if the format is not specified, it defaults to csv return CSV; } private static boolean findMagic(byte[] expected, byte[] actual) { int i = 0; for (byte expectedByte : expected) { if (actual[i++] != expectedByte && expectedByte != '?') { return false; } } return true; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/FieldUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/FieldUtils.java
package com.alibaba.excel.util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Map; import com.alibaba.excel.metadata.NullObject; import com.alibaba.excel.support.cglib.beans.BeanMap; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Apache Software Foundation (ASF) */ public class FieldUtils { public static Class<?> nullObjectClass = NullObject.class; private static final int START_RESOLVE_FIELD_LENGTH = 2; public static Class<?> getFieldClass(Map dataMap, String fieldName, Object value) { if (dataMap instanceof BeanMap) { Class<?> fieldClass = ((BeanMap)dataMap).getPropertyType(fieldName); if (fieldClass != null) { return fieldClass; } } return getFieldClass(value); } public static Class<?> getFieldClass(Object value) { if (value != null) { return value.getClass(); } return nullObjectClass; } /** * Parsing the name matching cglib。 * <pre> * null -&gt; null * string1 -&gt; string1 * String2 -&gt; string2 * sTring3 -&gt; STring3 * STring4 -&gt; STring4 * STRING5 -&gt; STRING5 * STRing6 -&gt; STRing6 * </pre> * * @param field field * @return field name. */ public static String resolveCglibFieldName(Field field) { if (field == null) { return null; } String fieldName = field.getName(); if (StringUtils.isBlank(fieldName) || fieldName.length() < START_RESOLVE_FIELD_LENGTH) { return fieldName; } char firstChar = fieldName.charAt(0); char secondChar = fieldName.charAt(1); if (Character.isUpperCase(firstChar) == Character.isUpperCase(secondChar)) { return fieldName; } if (Character.isUpperCase(firstChar)) { return buildFieldName(Character.toLowerCase(firstChar), fieldName); } return buildFieldName(Character.toUpperCase(firstChar), fieldName); } private static String buildFieldName(char firstChar, String fieldName) { return firstChar + fieldName.substring(1); } /** * Gets an accessible {@link Field} by name respecting scope. Superclasses/interfaces will be considered. * * @param cls the {@link Class} to reflect, must not be {@code null} * @param fieldName the field name to obtain * @return the Field object * @throws IllegalArgumentException if the class is {@code null}, or the field name is blank or empty */ public static Field getField(final Class<?> cls, final String fieldName) { final Field field = getField(cls, fieldName, false); MemberUtils.setAccessibleWorkaround(field); return field; } /** * Gets an accessible {@link Field} by name, breaking scope if requested. Superclasses/interfaces will be * considered. * * @param cls the {@link Class} to reflect, must not be {@code null} * @param fieldName the field name to obtain * @param forceAccess whether to break scope restrictions using the * {@link java.lang.reflect.AccessibleObject#setAccessible(boolean)} method. {@code false} will * only * match {@code public} fields. * @return the Field object * @throws NullPointerException if the class is {@code null} * @throws IllegalArgumentException if the field name is blank or empty or is matched at multiple places * in the inheritance hierarchy */ public static Field getField(final Class<?> cls, final String fieldName, final boolean forceAccess) { Validate.isTrue(cls != null, "The class must not be null"); Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty"); // FIXME is this workaround still needed? lang requires Java 6 // Sun Java 1.3 has a bugged implementation of getField hence we write the // code ourselves // getField() will return the Field object with the declaring class // set correctly to the class that declares the field. Thus requesting the // field on a subclass will return the field from the superclass. // // priority order for lookup: // searchclass private/protected/package/public // superclass protected/package/public // private/different package blocks access to further superclasses // implementedinterface public // check up the superclass hierarchy for (Class<?> acls = cls; acls != null; acls = acls.getSuperclass()) { try { final Field field = acls.getDeclaredField(fieldName); // getDeclaredField checks for non-public scopes as well // and it returns accurate results if (!Modifier.isPublic(field.getModifiers())) { if (forceAccess) { field.setAccessible(true); } else { continue; } } return field; } catch (final NoSuchFieldException ex) { // NOPMD // ignore } } // check the public interface case. This must be manually searched for // incase there is a public supersuperclass field hidden by a private/package // superclass field. Field match = null; for (final Class<?> class1 : ClassUtils.getAllInterfaces(cls)) { try { final Field test = class1.getField(fieldName); Validate.isTrue(match == null, "Reference to field %s is ambiguous relative to %s" + "; a matching field exists on two or more implemented interfaces.", fieldName, cls); match = test; } catch (final NoSuchFieldException ex) { // NOPMD // ignore } } return match; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/SheetUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/SheetUtils.java
package com.alibaba.excel.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.read.metadata.ReadSheet; import com.alibaba.excel.read.metadata.holder.ReadWorkbookHolder; /** * Sheet utils * * @author Jiaju Zhuang */ public class SheetUtils { private static final Logger LOGGER = LoggerFactory.getLogger(SheetUtils.class); private SheetUtils() {} /** * Match the parameters to the actual sheet * * @param readSheet actual sheet * @param analysisContext * @return */ public static ReadSheet match(ReadSheet readSheet, AnalysisContext analysisContext) { ReadWorkbookHolder readWorkbookHolder = analysisContext.readWorkbookHolder(); if (readWorkbookHolder.getReadAll()) { return readSheet; } for (ReadSheet parameterReadSheet : readWorkbookHolder.getParameterSheetDataList()) { if (parameterReadSheet == null) { continue; } if (parameterReadSheet.getSheetNo() == null && parameterReadSheet.getSheetName() == null) { if (LOGGER.isDebugEnabled()) { LOGGER.debug("The first is read by default."); } parameterReadSheet.setSheetNo(0); } boolean match = (parameterReadSheet.getSheetNo() != null && parameterReadSheet.getSheetNo().equals(readSheet.getSheetNo())); if (!match) { String parameterSheetName = parameterReadSheet.getSheetName(); if (!StringUtils.isEmpty(parameterSheetName)) { boolean autoTrim = (parameterReadSheet.getAutoTrim() != null && parameterReadSheet.getAutoTrim()) || (parameterReadSheet.getAutoTrim() == null && analysisContext.readWorkbookHolder().getGlobalConfiguration().getAutoTrim()); String sheetName = readSheet.getSheetName(); if (autoTrim) { parameterSheetName = parameterSheetName.trim(); sheetName = sheetName.trim(); } match = parameterSheetName.equals(sheetName); } } if (match) { readSheet.copyBasicParameter(parameterReadSheet); return readSheet; } } return null; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/ConverterUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/ConverterUtils.java
package com.alibaba.excel.util; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.Map; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.ConverterKeyBuild; import com.alibaba.excel.converters.ConverterKeyBuild.ConverterKey; import com.alibaba.excel.converters.NullableObjectConverter; import com.alibaba.excel.converters.ReadConverterContext; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.exception.ExcelDataConvertException; import com.alibaba.excel.metadata.data.CellData; import com.alibaba.excel.metadata.data.ReadCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.read.metadata.holder.ReadSheetHolder; /** * Converting objects * * @author Jiaju Zhuang **/ public class ConverterUtils { public static Class<?> defaultClassGeneric = String.class; private ConverterUtils() {} /** * Convert it into a String map * * @param cellDataMap * @param context * @return */ public static Map<Integer, String> convertToStringMap(Map<Integer, ReadCellData<?>> cellDataMap, AnalysisContext context) { Map<Integer, String> stringMap = MapUtils.newHashMapWithExpectedSize(cellDataMap.size()); ReadSheetHolder readSheetHolder = context.readSheetHolder(); int index = 0; for (Map.Entry<Integer, ReadCellData<?>> entry : cellDataMap.entrySet()) { Integer key = entry.getKey(); ReadCellData<?> cellData = entry.getValue(); while (index < key) { stringMap.put(index, null); index++; } index++; if (cellData.getType() == CellDataTypeEnum.EMPTY) { stringMap.put(key, null); continue; } Converter<?> converter = readSheetHolder.converterMap().get(ConverterKeyBuild.buildKey(String.class, cellData.getType())); if (converter == null) { throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), key, cellData, null, "Converter not found, convert " + cellData.getType() + " to String"); } try { stringMap.put(key, (String)(converter.convertToJavaData(new ReadConverterContext<>(cellData, null, context)))); } catch (Exception e) { throw new ExcelDataConvertException(context.readRowHolder().getRowIndex(), key, cellData, null, "Convert data " + cellData + " to String error ", e); } } return stringMap; } /** * Convert it into a Java object * * @param cellData * @param field * @param contentProperty * @param converterMap * @param context * @param rowIndex * @param columnIndex * @return */ public static Object convertToJavaObject(ReadCellData<?> cellData, Field field, ExcelContentProperty contentProperty, Map<ConverterKey, Converter<?>> converterMap, AnalysisContext context, Integer rowIndex, Integer columnIndex) { return convertToJavaObject(cellData, field, null, null, contentProperty, converterMap, context, rowIndex, columnIndex); } /** * Convert it into a Java object * * @param cellData * @param field * @param clazz * @param contentProperty * @param converterMap * @param context * @param rowIndex * @param columnIndex * @return */ public static Object convertToJavaObject(ReadCellData<?> cellData, Field field, Class<?> clazz, Class<?> classGeneric, ExcelContentProperty contentProperty, Map<ConverterKey, Converter<?>> converterMap, AnalysisContext context, Integer rowIndex, Integer columnIndex) { if (clazz == null) { if (field == null) { clazz = String.class; } else { clazz = field.getType(); } } if (clazz == CellData.class || clazz == ReadCellData.class) { ReadCellData<Object> cellDataReturn = cellData.clone(); cellDataReturn.setData( doConvertToJavaObject(cellData, getClassGeneric(field, classGeneric), contentProperty, converterMap, context, rowIndex, columnIndex)); return cellDataReturn; } return doConvertToJavaObject(cellData, clazz, contentProperty, converterMap, context, rowIndex, columnIndex); } private static Class<?> getClassGeneric(Field field, Class<?> classGeneric) { if (classGeneric != null) { return classGeneric; } if (field == null) { return defaultClassGeneric; } Type type = field.getGenericType(); if (!(type instanceof ParameterizedType)) { return defaultClassGeneric; } ParameterizedType parameterizedType = (ParameterizedType)type; Type[] types = parameterizedType.getActualTypeArguments(); if (types == null || types.length == 0) { return defaultClassGeneric; } Type actualType = types[0]; if (!(actualType instanceof Class<?>)) { return defaultClassGeneric; } return (Class<?>)actualType; } /** * @param cellData * @param clazz * @param contentProperty * @param converterMap * @param context * @param rowIndex * @param columnIndex * @return */ private static Object doConvertToJavaObject(ReadCellData<?> cellData, Class<?> clazz, ExcelContentProperty contentProperty, Map<ConverterKey, Converter<?>> converterMap, AnalysisContext context, Integer rowIndex, Integer columnIndex) { Converter<?> converter = null; if (contentProperty != null) { converter = contentProperty.getConverter(); } boolean canNotConverterEmpty = cellData.getType() == CellDataTypeEnum.EMPTY && !(converter instanceof NullableObjectConverter); if (canNotConverterEmpty) { return null; } if (converter == null) { converter = converterMap.get(ConverterKeyBuild.buildKey(clazz, cellData.getType())); } if (converter == null) { throw new ExcelDataConvertException(rowIndex, columnIndex, cellData, contentProperty, "Converter not found, convert " + cellData.getType() + " to " + clazz.getName()); } try { return converter.convertToJavaData(new ReadConverterContext<>(cellData, contentProperty, context)); } catch (Exception e) { throw new ExcelDataConvertException(rowIndex, columnIndex, cellData, contentProperty, "Convert data " + cellData + " to " + clazz + " error ", e); } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/MemberUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/MemberUtils.java
package com.alibaba.excel.util; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Member; import java.lang.reflect.Modifier; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Apache Software Foundation (ASF) */ public class MemberUtils { private static final int ACCESS_TEST = Modifier.PUBLIC | Modifier.PROTECTED | Modifier.PRIVATE; /** * XXX Default access superclass workaround. * * When a {@code public} class has a default access superclass with {@code public} members, * these members are accessible. Calling them from compiled code works fine. * Unfortunately, on some JVMs, using reflection to invoke these members * seems to (wrongly) prevent access even when the modifier is {@code public}. * Calling {@code setAccessible(true)} solves the problem but will only work from * sufficiently privileged code. Better workarounds would be gratefully * accepted. * @param o the AccessibleObject to set as accessible * @return a boolean indicating whether the accessibility of the object was set to true. */ static boolean setAccessibleWorkaround(final AccessibleObject o) { if (o == null || o.isAccessible()) { return false; } final Member m = (Member) o; if (!o.isAccessible() && Modifier.isPublic(m.getModifiers()) && isPackageAccess(m.getDeclaringClass().getModifiers())) { try { o.setAccessible(true); return true; } catch (final SecurityException e) { // NOPMD // ignore in favor of subsequent IllegalAccessException } } return false; } /** * Returns whether a given set of modifiers implies package access. * @param modifiers to test * @return {@code true} unless {@code package}/{@code protected}/{@code private} modifier detected */ static boolean isPackageAccess(final int modifiers) { return (modifiers & ACCESS_TEST) == 0; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/StringUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/StringUtils.java
package com.alibaba.excel.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Apache Software Foundation (ASF) */ public class StringUtils { private StringUtils() {} /** * A String for a space character. */ public static final String SPACE = " "; /** * The empty String {@code ""}. */ public static final String EMPTY = ""; /** * <p>Checks if a CharSequence is empty ("") or null.</p> * * <pre> * StringUtils.isEmpty(null) = true * StringUtils.isEmpty("") = true * StringUtils.isEmpty(" ") = false * StringUtils.isEmpty("bob") = false * StringUtils.isEmpty(" bob ") = false * </pre> * * <p>NOTE: This method changed in Lang version 2.0. * It no longer trims the CharSequence. * That functionality is available in isBlank().</p> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is empty or null */ public static boolean isEmpty(final CharSequence cs) { return cs == null || cs.length() == 0; } /** * <p>Checks if a CharSequence is empty (""), null or whitespace only.</p> * * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.isBlank(null) = true * StringUtils.isBlank("") = true * StringUtils.isBlank(" ") = true * StringUtils.isBlank("bob") = false * StringUtils.isBlank(" bob ") = false * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is null, empty or whitespace only */ public static boolean isBlank(final CharSequence cs) { int strLen; if (cs == null || (strLen = cs.length()) == 0) { return true; } for (int i = 0; i < strLen; i++) { if (!Character.isWhitespace(cs.charAt(i))) { return false; } } return true; } /** * <p>Checks if a CharSequence is not empty (""), not null and not whitespace only.</p> * * <p>Whitespace is defined by {@link Character#isWhitespace(char)}.</p> * * <pre> * StringUtils.isNotBlank(null) = false * StringUtils.isNotBlank("") = false * StringUtils.isNotBlank(" ") = false * StringUtils.isNotBlank("bob") = true * StringUtils.isNotBlank(" bob ") = true * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if the CharSequence is * not empty and not null and not whitespace only * @since 2.0 * @since 3.0 Changed signature from isNotBlank(String) to isNotBlank(CharSequence) */ public static boolean isNotBlank(final CharSequence cs) { return !isBlank(cs); } /** * <p>Compares two CharSequences, returning {@code true} if they represent * equal sequences of characters.</p> * * <p>{@code null}s are handled without exceptions. Two {@code null} * references are considered to be equal. The comparison is case sensitive.</p> * * <pre> * StringUtils.equals(null, null) = true * StringUtils.equals(null, "abc") = false * StringUtils.equals("abc", null) = false * StringUtils.equals("abc", "abc") = true * StringUtils.equals("abc", "ABC") = false * </pre> * * @param cs1 the first CharSequence, may be {@code null} * @param cs2 the second CharSequence, may be {@code null} * @return {@code true} if the CharSequences are equal (case-sensitive), or both {@code null} * @see Object#equals(Object) * @since 3.0 Changed signature from equals(String, String) to equals(CharSequence, CharSequence) */ public static boolean equals(final CharSequence cs1, final CharSequence cs2) { if (cs1 == cs2) { return true; } if (cs1 == null || cs2 == null) { return false; } if (cs1.length() != cs2.length()) { return false; } if (cs1 instanceof String && cs2 instanceof String) { return cs1.equals(cs2); } return regionMatches(cs1, false, 0, cs2, 0, cs1.length()); } /** * Green implementation of regionMatches. * * @param cs the {@code CharSequence} to be processed * @param ignoreCase whether or not to be case insensitive * @param thisStart the index to start on the {@code cs} CharSequence * @param substring the {@code CharSequence} to be looked for * @param start the index to start on the {@code substring} CharSequence * @param length character length of the region * @return whether the region matched */ public static boolean regionMatches(final CharSequence cs, final boolean ignoreCase, final int thisStart, final CharSequence substring, final int start, final int length) { if (cs instanceof String && substring instanceof String) { return ((String)cs).regionMatches(ignoreCase, thisStart, (String)substring, start, length); } int index1 = thisStart; int index2 = start; int tmpLen = length; // Extract these first so we detect NPEs the same as the java.lang.String version final int srcLen = cs.length() - thisStart; final int otherLen = substring.length() - start; // Check for invalid parameters if (thisStart < 0 || start < 0 || length < 0) { return false; } // Check that the regions are long enough if (srcLen < length || otherLen < length) { return false; } while (tmpLen-- > 0) { final char c1 = cs.charAt(index1++); final char c2 = substring.charAt(index2++); if (c1 == c2) { continue; } if (!ignoreCase) { return false; } // The same check as in String.regionMatches(): if (Character.toUpperCase(c1) != Character.toUpperCase(c2) && Character.toLowerCase(c1) != Character.toLowerCase(c2)) { return false; } } return true; } /** * <p>Checks if the CharSequence contains only Unicode digits. * A decimal point is not a Unicode digit and returns false.</p> * * <p>{@code null} will return {@code false}. * An empty CharSequence (length()=0) will return {@code false}.</p> * * <p>Note that the method does not allow for a leading sign, either positive or negative. * Also, if a String passes the numeric test, it may still generate a NumberFormatException * when parsed by Integer.parseInt or Long.parseLong, e.g. if the value is outside the range * for int or long respectively.</p> * * <pre> * StringUtils.isNumeric(null) = false * StringUtils.isNumeric("") = false * StringUtils.isNumeric(" ") = false * StringUtils.isNumeric("123") = true * StringUtils.isNumeric("\u0967\u0968\u0969") = true * StringUtils.isNumeric("12 3") = false * StringUtils.isNumeric("ab2c") = false * StringUtils.isNumeric("12-3") = false * StringUtils.isNumeric("12.3") = false * StringUtils.isNumeric("-123") = false * StringUtils.isNumeric("+123") = false * </pre> * * @param cs the CharSequence to check, may be null * @return {@code true} if only contains digits, and is non-null * @since 3.0 Changed signature from isNumeric(String) to isNumeric(CharSequence) * @since 3.0 Changed "" to return false and not true */ public static boolean isNumeric(final CharSequence cs) { if (isEmpty(cs)) { return false; } final int sz = cs.length(); for (int i = 0; i < sz; i++) { if (!Character.isDigit(cs.charAt(i))) { return false; } } return true; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/ClassUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/ClassUtils.java
package com.alibaba.excel.util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import com.alibaba.excel.annotation.ExcelIgnore; import com.alibaba.excel.annotation.ExcelIgnoreUnannotated; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.annotation.format.DateTimeFormat; import com.alibaba.excel.annotation.format.NumberFormat; import com.alibaba.excel.annotation.write.style.ContentFontStyle; import com.alibaba.excel.annotation.write.style.ContentStyle; import com.alibaba.excel.converters.AutoConverter; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.exception.ExcelCommonException; import com.alibaba.excel.metadata.ConfigurationHolder; import com.alibaba.excel.metadata.FieldCache; import com.alibaba.excel.metadata.FieldWrapper; import com.alibaba.excel.metadata.property.DateTimeFormatProperty; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.metadata.property.FontProperty; import com.alibaba.excel.metadata.property.NumberFormatProperty; import com.alibaba.excel.metadata.property.StyleProperty; import com.alibaba.excel.support.cglib.beans.BeanMap; import com.alibaba.excel.write.metadata.holder.WriteHolder; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.commons.collections4.CollectionUtils; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Apache Software Foundation (ASF) */ public class ClassUtils { /** * memory cache */ public static final Map<FieldCacheKey, FieldCache> FIELD_CACHE = new ConcurrentHashMap<>(); /** * thread local cache */ private static final ThreadLocal<Map<FieldCacheKey, FieldCache>> FIELD_THREAD_LOCAL = new ThreadLocal<>(); /** * The cache configuration information for each of the class */ public static final ConcurrentHashMap<Class<?>, Map<String, ExcelContentProperty>> CLASS_CONTENT_CACHE = new ConcurrentHashMap<>(); /** * The cache configuration information for each of the class */ private static final ThreadLocal<Map<Class<?>, Map<String, ExcelContentProperty>>> CLASS_CONTENT_THREAD_LOCAL = new ThreadLocal<>(); /** * The cache configuration information for each of the class */ public static final ConcurrentHashMap<ContentPropertyKey, ExcelContentProperty> CONTENT_CACHE = new ConcurrentHashMap<>(); /** * The cache configuration information for each of the class */ private static final ThreadLocal<Map<ContentPropertyKey, ExcelContentProperty>> CONTENT_THREAD_LOCAL = new ThreadLocal<>(); /** * Calculate the configuration information for the class * * @param dataMap * @param headClazz * @param fieldName * @return */ public static ExcelContentProperty declaredExcelContentProperty(Map<?, ?> dataMap, Class<?> headClazz, String fieldName, ConfigurationHolder configurationHolder) { Class<?> clazz = null; if (dataMap instanceof BeanMap) { Object bean = ((BeanMap)dataMap).getBean(); if (bean != null) { clazz = bean.getClass(); } } return getExcelContentProperty(clazz, headClazz, fieldName, configurationHolder); } private static ExcelContentProperty getExcelContentProperty(Class<?> clazz, Class<?> headClass, String fieldName, ConfigurationHolder configurationHolder) { switch (configurationHolder.globalConfiguration().getFiledCacheLocation()) { case THREAD_LOCAL: Map<ContentPropertyKey, ExcelContentProperty> contentCacheMap = CONTENT_THREAD_LOCAL.get(); if (contentCacheMap == null) { contentCacheMap = MapUtils.newHashMap(); CONTENT_THREAD_LOCAL.set(contentCacheMap); } return contentCacheMap.computeIfAbsent(buildKey(clazz, headClass, fieldName), key -> { return doGetExcelContentProperty(clazz, headClass, fieldName, configurationHolder); }); case MEMORY: return CONTENT_CACHE.computeIfAbsent(buildKey(clazz, headClass, fieldName), key -> { return doGetExcelContentProperty(clazz, headClass, fieldName, configurationHolder); }); case NONE: return doGetExcelContentProperty(clazz, headClass, fieldName, configurationHolder); default: throw new UnsupportedOperationException("unsupported enum"); } } private static ExcelContentProperty doGetExcelContentProperty(Class<?> clazz, Class<?> headClass, String fieldName, ConfigurationHolder configurationHolder) { ExcelContentProperty excelContentProperty = Optional.ofNullable( declaredFieldContentMap(clazz, configurationHolder)) .map(map -> map.get(fieldName)) .orElse(null); ExcelContentProperty headExcelContentProperty = Optional.ofNullable( declaredFieldContentMap(headClass, configurationHolder)) .map(map -> map.get(fieldName)) .orElse(null); ExcelContentProperty combineExcelContentProperty = new ExcelContentProperty(); combineExcelContentProperty(combineExcelContentProperty, headExcelContentProperty); if (clazz != headClass) { combineExcelContentProperty(combineExcelContentProperty, excelContentProperty); } return combineExcelContentProperty; } public static void combineExcelContentProperty(ExcelContentProperty combineExcelContentProperty, ExcelContentProperty excelContentProperty) { if (excelContentProperty == null) { return; } if (excelContentProperty.getField() != null) { combineExcelContentProperty.setField(excelContentProperty.getField()); } if (excelContentProperty.getConverter() != null) { combineExcelContentProperty.setConverter(excelContentProperty.getConverter()); } if (excelContentProperty.getDateTimeFormatProperty() != null) { combineExcelContentProperty.setDateTimeFormatProperty(excelContentProperty.getDateTimeFormatProperty()); } if (excelContentProperty.getNumberFormatProperty() != null) { combineExcelContentProperty.setNumberFormatProperty(excelContentProperty.getNumberFormatProperty()); } if (excelContentProperty.getContentStyleProperty() != null) { combineExcelContentProperty.setContentStyleProperty(excelContentProperty.getContentStyleProperty()); } if (excelContentProperty.getContentFontProperty() != null) { combineExcelContentProperty.setContentFontProperty(excelContentProperty.getContentFontProperty()); } } private static ContentPropertyKey buildKey(Class<?> clazz, Class<?> headClass, String fieldName) { return new ContentPropertyKey(clazz, headClass, fieldName); } private static Map<String, ExcelContentProperty> declaredFieldContentMap(Class<?> clazz, ConfigurationHolder configurationHolder) { if (clazz == null) { return null; } switch (configurationHolder.globalConfiguration().getFiledCacheLocation()) { case THREAD_LOCAL: Map<Class<?>, Map<String, ExcelContentProperty>> classContentCacheMap = CLASS_CONTENT_THREAD_LOCAL.get(); if (classContentCacheMap == null) { classContentCacheMap = MapUtils.newHashMap(); CLASS_CONTENT_THREAD_LOCAL.set(classContentCacheMap); } return classContentCacheMap.computeIfAbsent(clazz, key -> { return doDeclaredFieldContentMap(clazz); }); case MEMORY: return CLASS_CONTENT_CACHE.computeIfAbsent(clazz, key -> { return doDeclaredFieldContentMap(clazz); }); case NONE: return doDeclaredFieldContentMap(clazz); default: throw new UnsupportedOperationException("unsupported enum"); } } private static Map<String, ExcelContentProperty> doDeclaredFieldContentMap(Class<?> clazz) { if (clazz == null) { return null; } List<Field> tempFieldList = new ArrayList<>(); Class<?> tempClass = clazz; while (tempClass != null) { Collections.addAll(tempFieldList, tempClass.getDeclaredFields()); // Get the parent class and give it to yourself tempClass = tempClass.getSuperclass(); } ContentStyle parentContentStyle = clazz.getAnnotation(ContentStyle.class); ContentFontStyle parentContentFontStyle = clazz.getAnnotation(ContentFontStyle.class); Map<String, ExcelContentProperty> fieldContentMap = MapUtils.newHashMapWithExpectedSize( tempFieldList.size()); for (Field field : tempFieldList) { ExcelContentProperty excelContentProperty = new ExcelContentProperty(); excelContentProperty.setField(field); ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class); if (excelProperty != null) { Class<? extends Converter<?>> convertClazz = excelProperty.converter(); if (convertClazz != AutoConverter.class) { try { Converter<?> converter = convertClazz.getDeclaredConstructor().newInstance(); excelContentProperty.setConverter(converter); } catch (Exception e) { throw new ExcelCommonException( "Can not instance custom converter:" + convertClazz.getName()); } } } ContentStyle contentStyle = field.getAnnotation(ContentStyle.class); if (contentStyle == null) { contentStyle = parentContentStyle; } excelContentProperty.setContentStyleProperty(StyleProperty.build(contentStyle)); ContentFontStyle contentFontStyle = field.getAnnotation(ContentFontStyle.class); if (contentFontStyle == null) { contentFontStyle = parentContentFontStyle; } excelContentProperty.setContentFontProperty(FontProperty.build(contentFontStyle)); excelContentProperty.setDateTimeFormatProperty( DateTimeFormatProperty.build(field.getAnnotation(DateTimeFormat.class))); excelContentProperty.setNumberFormatProperty( NumberFormatProperty.build(field.getAnnotation(NumberFormat.class))); fieldContentMap.put(field.getName(), excelContentProperty); } return fieldContentMap; } /** * Parsing field in the class * * @param clazz Need to parse the class * @param configurationHolder configuration */ public static FieldCache declaredFields(Class<?> clazz, ConfigurationHolder configurationHolder) { switch (configurationHolder.globalConfiguration().getFiledCacheLocation()) { case THREAD_LOCAL: Map<FieldCacheKey, FieldCache> fieldCacheMap = FIELD_THREAD_LOCAL.get(); if (fieldCacheMap == null) { fieldCacheMap = MapUtils.newHashMap(); FIELD_THREAD_LOCAL.set(fieldCacheMap); } return fieldCacheMap.computeIfAbsent(new FieldCacheKey(clazz, configurationHolder), key -> { return doDeclaredFields(clazz, configurationHolder); }); case MEMORY: return FIELD_CACHE.computeIfAbsent(new FieldCacheKey(clazz, configurationHolder), key -> { return doDeclaredFields(clazz, configurationHolder); }); case NONE: return doDeclaredFields(clazz, configurationHolder); default: throw new UnsupportedOperationException("unsupported enum"); } } private static FieldCache doDeclaredFields(Class<?> clazz, ConfigurationHolder configurationHolder) { List<Field> tempFieldList = new ArrayList<>(); Class<?> tempClass = clazz; // When the parent class is null, it indicates that the parent class (Object class) has reached the top // level. while (tempClass != null) { Collections.addAll(tempFieldList, tempClass.getDeclaredFields()); // Get the parent class and give it to yourself tempClass = tempClass.getSuperclass(); } // Screening of field Map<Integer, List<FieldWrapper>> orderFieldMap = new TreeMap<>(); Map<Integer, FieldWrapper> indexFieldMap = new TreeMap<>(); Set<String> ignoreSet = new HashSet<>(); ExcelIgnoreUnannotated excelIgnoreUnannotated = clazz.getAnnotation(ExcelIgnoreUnannotated.class); for (Field field : tempFieldList) { declaredOneField(field, orderFieldMap, indexFieldMap, ignoreSet, excelIgnoreUnannotated); } Map<Integer, FieldWrapper> sortedFieldMap = buildSortedAllFieldMap(orderFieldMap, indexFieldMap); FieldCache fieldCache = new FieldCache(sortedFieldMap, indexFieldMap); if (!(configurationHolder instanceof WriteHolder)) { return fieldCache; } WriteHolder writeHolder = (WriteHolder)configurationHolder; boolean needIgnore = !CollectionUtils.isEmpty(writeHolder.excludeColumnFieldNames()) || !CollectionUtils.isEmpty(writeHolder.excludeColumnIndexes()) || !CollectionUtils.isEmpty(writeHolder.includeColumnFieldNames()) || !CollectionUtils.isEmpty(writeHolder.includeColumnIndexes()); if (!needIgnore) { return fieldCache; } // ignore filed Map<Integer, FieldWrapper> tempSortedFieldMap = MapUtils.newHashMap(); int index = 0; for (Map.Entry<Integer, FieldWrapper> entry : sortedFieldMap.entrySet()) { Integer key = entry.getKey(); FieldWrapper field = entry.getValue(); // The current field needs to be ignored if (writeHolder.ignore(field.getFieldName(), entry.getKey())) { ignoreSet.add(field.getFieldName()); indexFieldMap.remove(index); } else { // Mandatory sorted fields if (indexFieldMap.containsKey(key)) { tempSortedFieldMap.put(key, field); } else { // Need to reorder automatically // Check whether the current key is already in use while (tempSortedFieldMap.containsKey(index)) { index++; } tempSortedFieldMap.put(index++, field); } } } fieldCache.setSortedFieldMap(tempSortedFieldMap); // resort field resortField(writeHolder, fieldCache); return fieldCache; } /** * it only works when {@link WriteHolder#includeColumnFieldNames()} or * {@link WriteHolder#includeColumnIndexes()} has value * and {@link WriteHolder#orderByIncludeColumn()} is true **/ private static void resortField(WriteHolder writeHolder, FieldCache fieldCache) { if (!writeHolder.orderByIncludeColumn()) { return; } Map<Integer, FieldWrapper> indexFieldMap = fieldCache.getIndexFieldMap(); Collection<String> includeColumnFieldNames = writeHolder.includeColumnFieldNames(); if (!CollectionUtils.isEmpty(includeColumnFieldNames)) { // Field sorted map Map<String, Integer> filedIndexMap = MapUtils.newHashMap(); int fieldIndex = 0; for (String includeColumnFieldName : includeColumnFieldNames) { filedIndexMap.put(includeColumnFieldName, fieldIndex++); } // rebuild sortedFieldMap Map<Integer, FieldWrapper> tempSortedFieldMap = MapUtils.newHashMap(); fieldCache.getSortedFieldMap().forEach((index, field) -> { Integer tempFieldIndex = filedIndexMap.get(field.getFieldName()); if (tempFieldIndex != null) { tempSortedFieldMap.put(tempFieldIndex, field); // The user has redefined the ordering and the ordering of annotations needs to be invalidated if (!tempFieldIndex.equals(index)) { indexFieldMap.remove(index); } } }); fieldCache.setSortedFieldMap(tempSortedFieldMap); return; } Collection<Integer> includeColumnIndexes = writeHolder.includeColumnIndexes(); if (!CollectionUtils.isEmpty(includeColumnIndexes)) { // Index sorted map Map<Integer, Integer> filedIndexMap = MapUtils.newHashMap(); int fieldIndex = 0; for (Integer includeColumnIndex : includeColumnIndexes) { filedIndexMap.put(includeColumnIndex, fieldIndex++); } // rebuild sortedFieldMap Map<Integer, FieldWrapper> tempSortedFieldMap = MapUtils.newHashMap(); fieldCache.getSortedFieldMap().forEach((index, field) -> { Integer tempFieldIndex = filedIndexMap.get(index); // The user has redefined the ordering and the ordering of annotations needs to be invalidated if (tempFieldIndex != null) { tempSortedFieldMap.put(tempFieldIndex, field); } }); fieldCache.setSortedFieldMap(tempSortedFieldMap); } } private static Map<Integer, FieldWrapper> buildSortedAllFieldMap(Map<Integer, List<FieldWrapper>> orderFieldMap, Map<Integer, FieldWrapper> indexFieldMap) { Map<Integer, FieldWrapper> sortedAllFieldMap = new HashMap<>( (orderFieldMap.size() + indexFieldMap.size()) * 4 / 3 + 1); Map<Integer, FieldWrapper> tempIndexFieldMap = new HashMap<>(indexFieldMap); int index = 0; for (List<FieldWrapper> fieldList : orderFieldMap.values()) { for (FieldWrapper field : fieldList) { while (tempIndexFieldMap.containsKey(index)) { sortedAllFieldMap.put(index, tempIndexFieldMap.get(index)); tempIndexFieldMap.remove(index); index++; } sortedAllFieldMap.put(index, field); index++; } } sortedAllFieldMap.putAll(tempIndexFieldMap); return sortedAllFieldMap; } private static void declaredOneField(Field field, Map<Integer, List<FieldWrapper>> orderFieldMap, Map<Integer, FieldWrapper> indexFieldMap, Set<String> ignoreSet, ExcelIgnoreUnannotated excelIgnoreUnannotated) { String fieldName = FieldUtils.resolveCglibFieldName(field); FieldWrapper fieldWrapper = new FieldWrapper(); fieldWrapper.setField(field); fieldWrapper.setFieldName(fieldName); ExcelIgnore excelIgnore = field.getAnnotation(ExcelIgnore.class); if (excelIgnore != null) { ignoreSet.add(fieldName); return; } ExcelProperty excelProperty = field.getAnnotation(ExcelProperty.class); boolean noExcelProperty = excelProperty == null && excelIgnoreUnannotated != null; if (noExcelProperty) { ignoreSet.add(fieldName); return; } boolean isStaticFinalOrTransient = (Modifier.isStatic(field.getModifiers()) && Modifier.isFinal(field.getModifiers())) || Modifier.isTransient(field.getModifiers()); if (excelProperty == null && isStaticFinalOrTransient) { ignoreSet.add(fieldName); return; } // set heads if (excelProperty != null) { fieldWrapper.setHeads(excelProperty.value()); } if (excelProperty != null && excelProperty.index() >= 0) { if (indexFieldMap.containsKey(excelProperty.index())) { throw new ExcelCommonException( "The index of '" + indexFieldMap.get(excelProperty.index()).getFieldName() + "' and '" + field.getName() + "' must be inconsistent"); } indexFieldMap.put(excelProperty.index(), fieldWrapper); return; } int order = Integer.MAX_VALUE; if (excelProperty != null) { order = excelProperty.order(); } List<FieldWrapper> orderFieldList = orderFieldMap.computeIfAbsent(order, key -> ListUtils.newArrayList()); orderFieldList.add(fieldWrapper); } /** * <p>Gets a {@code List} of all interfaces implemented by the given * class and its superclasses.</p> * * <p>The order is determined by looking through each interface in turn as * declared in the source file and following its hierarchy up. Then each * superclass is considered in the same way. Later duplicates are ignored, * so the order is maintained.</p> * * @param cls the class to look up, may be {@code null} * @return the {@code List} of interfaces in order, * {@code null} if null input */ public static List<Class<?>> getAllInterfaces(final Class<?> cls) { if (cls == null) { return null; } final LinkedHashSet<Class<?>> interfacesFound = new LinkedHashSet<>(); getAllInterfaces(cls, interfacesFound); return new ArrayList<>(interfacesFound); } /** * Gets the interfaces for the specified class. * * @param cls the class to look up, may be {@code null} * @param interfacesFound the {@code Set} of interfaces for the class */ private static void getAllInterfaces(Class<?> cls, final HashSet<Class<?>> interfacesFound) { while (cls != null) { final Class<?>[] interfaces = cls.getInterfaces(); for (final Class<?> i : interfaces) { if (interfacesFound.add(i)) { getAllInterfaces(i, interfacesFound); } } cls = cls.getSuperclass(); } } @Getter @Setter @EqualsAndHashCode @AllArgsConstructor public static class ContentPropertyKey { private Class<?> clazz; private Class<?> headClass; private String fieldName; } @Data public static class FieldCacheKey { private Class<?> clazz; private Collection<String> excludeColumnFieldNames; private Collection<Integer> excludeColumnIndexes; private Collection<String> includeColumnFieldNames; private Collection<Integer> includeColumnIndexes; FieldCacheKey(Class<?> clazz, ConfigurationHolder configurationHolder) { this.clazz = clazz; if (configurationHolder instanceof WriteHolder) { WriteHolder writeHolder = (WriteHolder)configurationHolder; this.excludeColumnFieldNames = writeHolder.excludeColumnFieldNames(); this.excludeColumnIndexes = writeHolder.excludeColumnIndexes(); this.includeColumnFieldNames = writeHolder.includeColumnFieldNames(); this.includeColumnIndexes = writeHolder.includeColumnIndexes(); } } } public static void removeThreadLocalCache() { FIELD_THREAD_LOCAL.remove(); CLASS_CONTENT_THREAD_LOCAL.remove(); CONTENT_THREAD_LOCAL.remove(); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/NumberUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/NumberUtils.java
package com.alibaba.excel.util; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.ParseException; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.metadata.property.ExcelContentProperty; /** * Number utils * * @author Jiaju Zhuang */ public class NumberUtils { private NumberUtils() {} /** * format * * @param num * @param contentProperty * @return */ public static String format(Number num, ExcelContentProperty contentProperty) { if (contentProperty == null || contentProperty.getNumberFormatProperty() == null || StringUtils.isEmpty(contentProperty.getNumberFormatProperty().getFormat())) { if (num instanceof BigDecimal) { return ((BigDecimal)num).toPlainString(); } else { return num.toString(); } } String format = contentProperty.getNumberFormatProperty().getFormat(); RoundingMode roundingMode = contentProperty.getNumberFormatProperty().getRoundingMode(); DecimalFormat decimalFormat = new DecimalFormat(format); decimalFormat.setRoundingMode(roundingMode); return decimalFormat.format(num); } /** * format * * @param num * @param contentProperty * @return */ public static WriteCellData<?> formatToCellDataString(Number num, ExcelContentProperty contentProperty) { return new WriteCellData<>(format(num, contentProperty)); } /** * format * * @param num * @param contentProperty * @return */ public static WriteCellData<?> formatToCellData(Number num, ExcelContentProperty contentProperty) { WriteCellData<?> cellData = new WriteCellData<>(new BigDecimal(num.toString())); if (contentProperty != null && contentProperty.getNumberFormatProperty() != null && StringUtils.isNotBlank(contentProperty.getNumberFormatProperty().getFormat())) { WorkBookUtil.fillDataFormat(cellData, contentProperty.getNumberFormatProperty().getFormat(), null); } return cellData; } /** * parse * * @param string * @param contentProperty * @return */ public static Short parseShort(String string, ExcelContentProperty contentProperty) throws ParseException { if (!hasFormat(contentProperty)) { return new BigDecimal(string).shortValue(); } return parse(string, contentProperty).shortValue(); } /** * parse * * @param string * @param contentProperty * @return */ public static Long parseLong(String string, ExcelContentProperty contentProperty) throws ParseException { if (!hasFormat(contentProperty)) { return new BigDecimal(string).longValue(); } return parse(string, contentProperty).longValue(); } /** * parse Integer from string * * @param string An integer read in string format * @param contentProperty Properties of the content read in * @return An integer converted from a string */ public static Integer parseInteger(String string, ExcelContentProperty contentProperty) throws ParseException { if (!hasFormat(contentProperty)) { return new BigDecimal(string).intValue(); } return parse(string, contentProperty).intValue(); } /** * parse * * @param string * @param contentProperty * @return */ public static Float parseFloat(String string, ExcelContentProperty contentProperty) throws ParseException { if (!hasFormat(contentProperty)) { return new BigDecimal(string).floatValue(); } return parse(string, contentProperty).floatValue(); } /** * parse * * @param string * @param contentProperty * @return */ public static BigDecimal parseBigDecimal(String string, ExcelContentProperty contentProperty) throws ParseException { if (!hasFormat(contentProperty)) { return new BigDecimal(string); } return new BigDecimal(parse(string, contentProperty).toString()); } /** * parse * * @param string * @param contentProperty * @return */ public static Byte parseByte(String string, ExcelContentProperty contentProperty) throws ParseException { if (!hasFormat(contentProperty)) { return new BigDecimal(string).byteValue(); } return parse(string, contentProperty).byteValue(); } /** * parse * * @param string * @param contentProperty * @return */ public static Double parseDouble(String string, ExcelContentProperty contentProperty) throws ParseException { if (!hasFormat(contentProperty)) { return new BigDecimal(string).doubleValue(); } return parse(string, contentProperty).doubleValue(); } private static boolean hasFormat(ExcelContentProperty contentProperty) { return contentProperty != null && contentProperty.getNumberFormatProperty() != null && !StringUtils.isEmpty(contentProperty.getNumberFormatProperty().getFormat()); } /** * parse * * @param string * @param contentProperty * @return * @throws ParseException */ private static Number parse(String string, ExcelContentProperty contentProperty) throws ParseException { String format = contentProperty.getNumberFormatProperty().getFormat(); RoundingMode roundingMode = contentProperty.getNumberFormatProperty().getRoundingMode(); DecimalFormat decimalFormat = new DecimalFormat(format); decimalFormat.setRoundingMode(roundingMode); decimalFormat.setParseBigDecimal(true); return decimalFormat.parse(string); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/FileUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/FileUtils.java
package com.alibaba.excel.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.UUID; import com.alibaba.excel.exception.ExcelAnalysisException; import com.alibaba.excel.exception.ExcelCommonException; import org.apache.poi.util.TempFile; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Apache Software Foundation (ASF) */ public class FileUtils { public static final String POI_FILES = "poifiles"; public static final String EX_CACHE = "excache"; /** * If a server has multiple projects in use at the same time, a directory with the same name will be created under * the temporary directory, but each project is run by a different user, so there is a permission problem, so each * project creates a unique UUID as a separate Temporary Files. */ private static String tempFilePrefix = System.getProperty(TempFile.JAVA_IO_TMPDIR) + File.separator + UUID.randomUUID().toString() + File.separator; /** * Used to store poi temporary files. */ private static String poiFilesPath = tempFilePrefix + POI_FILES + File.separator; /** * Used to store easy excel temporary files. */ private static String cachePath = tempFilePrefix + EX_CACHE + File.separator; private static final int WRITE_BUFF_SIZE = 8192; private FileUtils() {} static { // Create a temporary directory in advance File tempFile = new File(tempFilePrefix); createDirectory(tempFile); tempFile.deleteOnExit(); // Initialize the cache directory File cacheFile = new File(cachePath); createDirectory(cacheFile); } /** * Reads the contents of a file into a byte array. * The file is always closed. * * @param file * @return * @throws IOException */ public static byte[] readFileToByteArray(final File file) throws IOException { InputStream in = openInputStream(file); try { final long fileLength = file.length(); return fileLength > 0 ? IoUtils.toByteArray(in, (int)fileLength) : IoUtils.toByteArray(in); } finally { in.close(); } } /** * Opens a {@link FileInputStream} for the specified file, providing better error messages than simply calling * <code>new FileInputStream(file)</code>. * <p> * At the end of the method either the stream will be successfully opened, or an exception will have been thrown. * <p> * An exception is thrown if the file does not exist. An exception is thrown if the file object exists but is a * directory. An exception is thrown if the file exists but cannot be read. * * @param file * @return * @throws IOException */ public static FileInputStream openInputStream(final File file) throws IOException { if (file.exists()) { if (file.isDirectory()) { throw new IOException("File '" + file + "' exists but is a directory"); } if (file.canRead() == false) { throw new IOException("File '" + file + "' cannot be read"); } } else { throw new FileNotFoundException("File '" + file + "' does not exist"); } return new FileInputStream(file); } /** * Write inputStream to file * * @param file file * @param inputStream inputStream */ public static void writeToFile(File file, InputStream inputStream) { writeToFile(file, inputStream, true); } /** * Write inputStream to file * * @param file file * @param inputStream inputStream * @param closeInputStream closeInputStream */ public static void writeToFile(File file, InputStream inputStream, boolean closeInputStream) { OutputStream outputStream = null; try { outputStream = new FileOutputStream(file); int bytesRead; byte[] buffer = new byte[WRITE_BUFF_SIZE]; while ((bytesRead = inputStream.read(buffer, 0, WRITE_BUFF_SIZE)) != -1) { outputStream.write(buffer, 0, bytesRead); } } catch (Exception e) { throw new ExcelAnalysisException("Can not create temporary file!", e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { throw new ExcelAnalysisException("Can not close 'outputStream'!", e); } } if (inputStream != null && closeInputStream) { try { inputStream.close(); } catch (IOException e) { throw new ExcelAnalysisException("Can not close 'inputStream'", e); } } } } public static void createPoiFilesDirectory() { TempFile.setTempFileCreationStrategy(new EasyExcelTempFileCreationStrategy()); } public static File createCacheTmpFile() { return createDirectory(new File(cachePath + UUID.randomUUID().toString())); } public static File createTmpFile(String fileName) { File directory = createDirectory(new File(tempFilePrefix)); return new File(directory, fileName); } /** * @param directory */ public static File createDirectory(File directory) { if (!directory.exists() && !directory.mkdirs()) { throw new ExcelCommonException("Cannot create directory:" + directory.getAbsolutePath()); } return directory; } /** * delete file * * @param file */ public static void delete(File file) { if (file.isFile()) { file.delete(); return; } if (file.isDirectory()) { File[] childFiles = file.listFiles(); if (childFiles == null || childFiles.length == 0) { file.delete(); return; } for (int i = 0; i < childFiles.length; i++) { delete(childFiles[i]); } file.delete(); } } public static String getTempFilePrefix() { return tempFilePrefix; } public static void setTempFilePrefix(String tempFilePrefix) { FileUtils.tempFilePrefix = tempFilePrefix; } public static String getPoiFilesPath() { return poiFilesPath; } public static void setPoiFilesPath(String poiFilesPath) { FileUtils.poiFilesPath = poiFilesPath; } public static String getCachePath() { return cachePath; } public static void setCachePath(String cachePath) { FileUtils.cachePath = cachePath; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/DateUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/DateUtils.java
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package com.alibaba.excel.util; import java.math.BigDecimal; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.ZoneId; import java.time.format.DateTimeFormatter; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.regex.Pattern; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.util.LocaleUtil; /** * Date utils * * @author Jiaju Zhuang **/ public class DateUtils { /** * Is a cache of dates */ private static final ThreadLocal<Map<Short, Boolean>> DATE_THREAD_LOCAL = new ThreadLocal<>(); /** * Is a cache of dates */ private static final ThreadLocal<Map<String, SimpleDateFormat>> DATE_FORMAT_THREAD_LOCAL = new ThreadLocal<>(); /** * The following patterns are used in {@link #isADateFormat(Short, String)} */ private static final Pattern date_ptrn1 = Pattern.compile("^\\[\\$\\-.*?\\]"); private static final Pattern date_ptrn2 = Pattern.compile("^\\[[a-zA-Z]+\\]"); private static final Pattern date_ptrn3a = Pattern.compile("[yYmMdDhHsS]"); // add "\u5e74 \u6708 \u65e5" for Chinese/Japanese date format:2017 \u5e74 2 \u6708 7 \u65e5 private static final Pattern date_ptrn3b = Pattern.compile("^[\\[\\]yYmMdDhHsS\\-T/\u5e74\u6708\u65e5,. :\"\\\\]+0*[ampAMP/]*$"); // elapsed time patterns: [h],[m] and [s] private static final Pattern date_ptrn4 = Pattern.compile("^\\[([hH]+|[mM]+|[sS]+)\\]"); // for format which start with "[DBNum1]" or "[DBNum2]" or "[DBNum3]" could be a Chinese date private static final Pattern date_ptrn5 = Pattern.compile("^\\[DBNum(1|2|3)\\]"); // for format which start with "年" or "月" or "日" or "时" or "分" or "秒" could be a Chinese date private static final Pattern date_ptrn6 = Pattern.compile("(年|月|日|时|分|秒)+"); public static final String DATE_FORMAT_10 = "yyyy-MM-dd"; public static final String DATE_FORMAT_14 = "yyyyMMddHHmmss"; public static final String DATE_FORMAT_16 = "yyyy-MM-dd HH:mm"; public static final String DATE_FORMAT_16_FORWARD_SLASH = "yyyy/MM/dd HH:mm"; public static final String DATE_FORMAT_17 = "yyyyMMdd HH:mm:ss"; public static final String DATE_FORMAT_19 = "yyyy-MM-dd HH:mm:ss"; public static final String DATE_FORMAT_19_FORWARD_SLASH = "yyyy/MM/dd HH:mm:ss"; private static final String MINUS = "-"; public static String defaultDateFormat = DATE_FORMAT_19; public static String defaultLocalDateFormat = DATE_FORMAT_10; public static final int SECONDS_PER_MINUTE = 60; public static final int MINUTES_PER_HOUR = 60; public static final int HOURS_PER_DAY = 24; public static final int SECONDS_PER_DAY = (HOURS_PER_DAY * MINUTES_PER_HOUR * SECONDS_PER_MINUTE); // used to specify that date is invalid private static final int BAD_DATE = -1; public static final long DAY_MILLISECONDS = SECONDS_PER_DAY * 1000L; private DateUtils() {} /** * convert string to date * * @param dateString * @param dateFormat * @return * @throws ParseException */ public static Date parseDate(String dateString, String dateFormat) throws ParseException { if (StringUtils.isEmpty(dateFormat)) { dateFormat = switchDateFormat(dateString); } return getCacheDateFormat(dateFormat).parse(dateString); } /** * convert string to date * * @param dateString * @param dateFormat * @param local * @return */ public static LocalDateTime parseLocalDateTime(String dateString, String dateFormat, Locale local) { if (StringUtils.isEmpty(dateFormat)) { dateFormat = switchDateFormat(dateString); } if (local == null) { return LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern(dateFormat)); } else { return LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern(dateFormat, local)); } } /** * convert string to date * * @param dateString * @param dateFormat * @param local * @return */ public static LocalDate parseLocalDate(String dateString, String dateFormat, Locale local) { if (StringUtils.isEmpty(dateFormat)) { dateFormat = switchDateFormat(dateString); } if (local == null) { return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(dateFormat)); } else { return LocalDate.parse(dateString, DateTimeFormatter.ofPattern(dateFormat, local)); } } /** * convert string to date * * @param dateString * @return * @throws ParseException */ public static Date parseDate(String dateString) throws ParseException { return parseDate(dateString, switchDateFormat(dateString)); } /** * switch date format * * @param dateString * @return */ public static String switchDateFormat(String dateString) { int length = dateString.length(); switch (length) { case 19: if (dateString.contains(MINUS)) { return DATE_FORMAT_19; } else { return DATE_FORMAT_19_FORWARD_SLASH; } case 16: if (dateString.contains(MINUS)) { return DATE_FORMAT_16; } else { return DATE_FORMAT_16_FORWARD_SLASH; } case 17: return DATE_FORMAT_17; case 14: return DATE_FORMAT_14; case 10: return DATE_FORMAT_10; default: throw new IllegalArgumentException("can not find date format for:" + dateString); } } /** * Format date * <p> * yyyy-MM-dd HH:mm:ss * * @param date * @return */ public static String format(Date date) { return format(date, null); } /** * Format date * * @param date * @param dateFormat * @return */ public static String format(Date date, String dateFormat) { if (date == null) { return null; } if (StringUtils.isEmpty(dateFormat)) { dateFormat = defaultDateFormat; } return getCacheDateFormat(dateFormat).format(date); } /** * Format date * * @param date * @param dateFormat * @return */ public static String format(LocalDateTime date, String dateFormat, Locale local) { if (date == null) { return null; } if (StringUtils.isEmpty(dateFormat)) { dateFormat = defaultDateFormat; } if (local == null) { return date.format(DateTimeFormatter.ofPattern(dateFormat)); } else { return date.format(DateTimeFormatter.ofPattern(dateFormat, local)); } } /** * Format date * * @param date * @param dateFormat * @return */ public static String format(LocalDate date, String dateFormat) { return format(date, dateFormat, null); } /** * Format date * * @param date * @param dateFormat * @return */ public static String format(LocalDate date, String dateFormat, Locale local) { if (date == null) { return null; } if (StringUtils.isEmpty(dateFormat)) { dateFormat = defaultLocalDateFormat; } if (local == null) { return date.format(DateTimeFormatter.ofPattern(dateFormat)); } else { return date.format(DateTimeFormatter.ofPattern(dateFormat, local)); } } /** * Format date * * @param date * @param dateFormat * @return */ public static String format(LocalDateTime date, String dateFormat) { return format(date, dateFormat, null); } /** * Format date * * @param date * @param dateFormat * @return */ public static String format(BigDecimal date, Boolean use1904windowing, String dateFormat) { if (date == null) { return null; } LocalDateTime localDateTime = DateUtil.getLocalDateTime(date.doubleValue(), BooleanUtils.isTrue(use1904windowing), true); return format(localDateTime, dateFormat); } private static DateFormat getCacheDateFormat(String dateFormat) { Map<String, SimpleDateFormat> dateFormatMap = DATE_FORMAT_THREAD_LOCAL.get(); if (dateFormatMap == null) { dateFormatMap = new HashMap<String, SimpleDateFormat>(); DATE_FORMAT_THREAD_LOCAL.set(dateFormatMap); } else { SimpleDateFormat dateFormatCached = dateFormatMap.get(dateFormat); if (dateFormatCached != null) { return dateFormatCached; } } SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateFormat); dateFormatMap.put(dateFormat, simpleDateFormat); return simpleDateFormat; } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.util.Date. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date is not a valid Excel date */ public static Date getJavaDate(double date, boolean use1904windowing) { Calendar calendar = getJavaCalendar(date, use1904windowing, null, true); return calendar == null ? null : calendar.getTime(); } /** * Get EXCEL date as Java Calendar with given time zone. * @param date The Excel date. * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @param timeZone The TimeZone to evaluate the date in * @param roundSeconds round to closest second * @return Java representation of the date, or null if date is not a valid Excel date */ public static Calendar getJavaCalendar(double date, boolean use1904windowing, TimeZone timeZone, boolean roundSeconds) { if (!isValidExcelDate(date)) { return null; } int wholeDays = (int)Math.floor(date); int millisecondsInDay = (int)((date - wholeDays) * DAY_MILLISECONDS + 0.5); Calendar calendar; if (timeZone != null) { calendar = LocaleUtil.getLocaleCalendar(timeZone); } else { calendar = LocaleUtil.getLocaleCalendar(); // using default time-zone } setCalendar(calendar, wholeDays, millisecondsInDay, use1904windowing, roundSeconds); return calendar; } public static void setCalendar(Calendar calendar, int wholeDays, int millisecondsInDay, boolean use1904windowing, boolean roundSeconds) { int startYear = 1900; int dayAdjust = -1; // Excel thinks 2/29/1900 is a valid date, which it isn't if (use1904windowing) { startYear = 1904; dayAdjust = 1; // 1904 date windowing uses 1/2/1904 as the first day } else if (wholeDays < 61) { // Date is prior to 3/1/1900, so adjust because Excel thinks 2/29/1900 exists // If Excel date == 2/29/1900, will become 3/1/1900 in Java representation dayAdjust = 0; } calendar.set(startYear, Calendar.JANUARY, wholeDays + dayAdjust, 0, 0, 0); calendar.set(Calendar.MILLISECOND, millisecondsInDay); if (calendar.get(Calendar.MILLISECOND) == 0) { calendar.clear(Calendar.MILLISECOND); } if (roundSeconds) { // This is different from poi where you need to change 500 to 499 calendar.add(Calendar.MILLISECOND, 499); calendar.clear(Calendar.MILLISECOND); } } /** * Given a double, checks if it is a valid Excel date. * * @return true if valid * @param value the double value */ public static boolean isValidExcelDate(double value) { return (value > -Double.MIN_VALUE); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.time.LocalDateTime. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date is not a valid Excel date */ public static LocalDateTime getLocalDateTime(double date, boolean use1904windowing) { return DateUtil.getLocalDateTime(date, use1904windowing, true); } /** * Given an Excel date with either 1900 or 1904 date windowing, * converts it to a java.time.LocalDate. * * Excel Dates and Times are stored without any timezone * information. If you know (through other means) that your file * uses a different TimeZone to the system default, you can use * this version of the getJavaDate() method to handle it. * * @param date The Excel date. * @param use1904windowing true if date uses 1904 windowing, * or false if using 1900 date windowing. * @return Java representation of the date, or null if date is not a valid Excel date */ public static LocalDate getLocalDate(double date, boolean use1904windowing) { LocalDateTime localDateTime = getLocalDateTime(date, use1904windowing); return localDateTime == null ? null : localDateTime.toLocalDate(); } /** * Determine if it is a date format. * * @param formatIndex * @param formatString * @return */ public static boolean isADateFormat(Short formatIndex, String formatString) { if (formatIndex == null) { return false; } Map<Short, Boolean> isDateCache = DATE_THREAD_LOCAL.get(); if (isDateCache == null) { isDateCache = MapUtils.newHashMap(); DATE_THREAD_LOCAL.set(isDateCache); } else { Boolean isDatecachedDataList = isDateCache.get(formatIndex); if (isDatecachedDataList != null) { return isDatecachedDataList; } } boolean isDate = isADateFormatUncached(formatIndex, formatString); isDateCache.put(formatIndex, isDate); return isDate; } /** * Determine if it is a date format. * * @param formatIndex * @param formatString * @return */ public static boolean isADateFormatUncached(Short formatIndex, String formatString) { // First up, is this an internal date format? if (isInternalDateFormat(formatIndex)) { return true; } if (StringUtils.isEmpty(formatString)) { return false; } String fs = formatString; final int length = fs.length(); StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { char c = fs.charAt(i); if (i < length - 1) { char nc = fs.charAt(i + 1); if (c == '\\') { switch (nc) { case '-': case ',': case '.': case ' ': case '\\': // skip current '\' and continue to the next char continue; } } else if (c == ';' && nc == '@') { i++; // skip ";@" duplets continue; } } sb.append(c); } fs = sb.toString(); // short-circuit if it indicates elapsed time: [h], [m] or [s] if (date_ptrn4.matcher(fs).matches()) { return true; } // If it starts with [DBNum1] or [DBNum2] or [DBNum3] // then it could be a Chinese date fs = date_ptrn5.matcher(fs).replaceAll(""); // If it starts with [$-...], then could be a date, but // who knows what that starting bit is all about fs = date_ptrn1.matcher(fs).replaceAll(""); // If it starts with something like [Black] or [Yellow], // then it could be a date fs = date_ptrn2.matcher(fs).replaceAll(""); // You're allowed something like dd/mm/yy;[red]dd/mm/yy // which would place dates before 1900/1904 in red // For now, only consider the first one final int separatorIndex = fs.indexOf(';'); if (0 < separatorIndex && separatorIndex < fs.length() - 1) { fs = fs.substring(0, separatorIndex); } // Ensure it has some date letters in it // (Avoids false positives on the rest of pattern 3) if (!date_ptrn3a.matcher(fs).find()) { return false; } // If we get here, check it's only made up, in any case, of: // y m d h s - \ / , . : [ ] T // optionally followed by AM/PM boolean result = date_ptrn3b.matcher(fs).matches(); if (result) { return true; } result = date_ptrn6.matcher(fs).find(); return result; } /** * Given a format ID this will check whether the format represents an internal excel date format or not. * * @see #isADateFormat(Short, String) */ public static boolean isInternalDateFormat(short format) { switch (format) { // Internal Date Formats as described on page 427 in // Microsoft Excel Dev's Kit... // 14-22 case 0x0e: case 0x0f: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: // 45-47 case 0x2d: case 0x2e: case 0x2f: return true; } return false; } public static void removeThreadLocalCache() { DATE_THREAD_LOCAL.remove(); DATE_FORMAT_THREAD_LOCAL.remove(); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/BeanMapUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/BeanMapUtils.java
package com.alibaba.excel.util; import com.alibaba.excel.support.cglib.beans.BeanMap; import com.alibaba.excel.support.cglib.core.DefaultNamingPolicy; /** * bean utils * * @author Jiaju Zhuang */ public class BeanMapUtils { /** * Helper method to create a new <code>BeanMap</code>. For finer * control over the generated instance, use a new instance of * <code>BeanMap.Generator</code> instead of this static method. * * Custom naming policy to prevent null pointer exceptions. * see: https://github.com/alibaba/easyexcel/issues/2064 * * @param bean the JavaBean underlying the map * @return a new <code>BeanMap</code> instance */ public static BeanMap create(Object bean) { BeanMap.Generator gen = new BeanMap.Generator(); gen.setBean(bean); gen.setContextClass(bean.getClass()); gen.setNamingPolicy(EasyExcelNamingPolicy.INSTANCE); return gen.create(); } public static class EasyExcelNamingPolicy extends DefaultNamingPolicy { public static final EasyExcelNamingPolicy INSTANCE = new EasyExcelNamingPolicy(); @Override protected String getTag() { return "ByEasyExcelCGLIB"; } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/WriteHandlerUtils.java
package com.alibaba.excel.util; import com.alibaba.excel.context.WriteContext; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.property.ExcelContentProperty; import com.alibaba.excel.write.handler.chain.CellHandlerExecutionChain; import com.alibaba.excel.write.handler.chain.RowHandlerExecutionChain; import com.alibaba.excel.write.handler.chain.SheetHandlerExecutionChain; import com.alibaba.excel.write.handler.chain.WorkbookHandlerExecutionChain; import com.alibaba.excel.write.handler.context.CellWriteHandlerContext; import com.alibaba.excel.write.handler.context.RowWriteHandlerContext; import com.alibaba.excel.write.handler.context.SheetWriteHandlerContext; import com.alibaba.excel.write.handler.context.WorkbookWriteHandlerContext; import com.alibaba.excel.write.metadata.holder.AbstractWriteHolder; import lombok.extern.slf4j.Slf4j; import org.apache.poi.ss.usermodel.Row; /** * Write handler utils * * @author Jiaju Zhuang */ @Slf4j public class WriteHandlerUtils { private WriteHandlerUtils() {} public static WorkbookWriteHandlerContext createWorkbookWriteHandlerContext(WriteContext writeContext) { WorkbookWriteHandlerContext context = new WorkbookWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder()); writeContext.writeWorkbookHolder().setWorkbookWriteHandlerContext(context); return context; } public static void beforeWorkbookCreate(WorkbookWriteHandlerContext context) { beforeWorkbookCreate(context, false); } public static void beforeWorkbookCreate(WorkbookWriteHandlerContext context, boolean runOwn) { WorkbookHandlerExecutionChain workbookHandlerExecutionChain = getWorkbookHandlerExecutionChain(context, runOwn); if (workbookHandlerExecutionChain != null) { workbookHandlerExecutionChain.beforeWorkbookCreate(context); } } public static void afterWorkbookCreate(WorkbookWriteHandlerContext context) { afterWorkbookCreate(context, false); } public static void afterWorkbookCreate(WorkbookWriteHandlerContext context, boolean runOwn) { WorkbookHandlerExecutionChain workbookHandlerExecutionChain = getWorkbookHandlerExecutionChain(context, runOwn); if (workbookHandlerExecutionChain != null) { workbookHandlerExecutionChain.afterWorkbookCreate(context); } } private static WorkbookHandlerExecutionChain getWorkbookHandlerExecutionChain(WorkbookWriteHandlerContext context, boolean runOwn) { AbstractWriteHolder abstractWriteHolder = (AbstractWriteHolder)context.getWriteContext().currentWriteHolder(); if (runOwn) { return abstractWriteHolder.getOwnWorkbookHandlerExecutionChain(); } else { return abstractWriteHolder.getWorkbookHandlerExecutionChain(); } } public static void afterWorkbookDispose(WorkbookWriteHandlerContext context) { WorkbookHandlerExecutionChain workbookHandlerExecutionChain = getWorkbookHandlerExecutionChain(context, false); if (workbookHandlerExecutionChain != null) { workbookHandlerExecutionChain.afterWorkbookDispose(context); } } public static SheetWriteHandlerContext createSheetWriteHandlerContext(WriteContext writeContext) { return new SheetWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(), writeContext.writeSheetHolder()); } public static void beforeSheetCreate(SheetWriteHandlerContext context) { beforeSheetCreate(context, false); } public static void beforeSheetCreate(SheetWriteHandlerContext context, boolean runOwn) { SheetHandlerExecutionChain sheetHandlerExecutionChain = getSheetHandlerExecutionChain(context, runOwn); if (sheetHandlerExecutionChain != null) { sheetHandlerExecutionChain.beforeSheetCreate(context); } } public static void afterSheetCreate(SheetWriteHandlerContext context) { afterSheetCreate(context, false); } public static void afterSheetCreate(SheetWriteHandlerContext context, boolean runOwn) { SheetHandlerExecutionChain sheetHandlerExecutionChain = getSheetHandlerExecutionChain(context, runOwn); if (sheetHandlerExecutionChain != null) { sheetHandlerExecutionChain.afterSheetCreate(context); } } private static SheetHandlerExecutionChain getSheetHandlerExecutionChain(SheetWriteHandlerContext context, boolean runOwn) { AbstractWriteHolder abstractWriteHolder = (AbstractWriteHolder)context.getWriteContext().currentWriteHolder(); if (runOwn) { return abstractWriteHolder.getOwnSheetHandlerExecutionChain(); } else { return abstractWriteHolder.getSheetHandlerExecutionChain(); } } public static CellWriteHandlerContext createCellWriteHandlerContext(WriteContext writeContext, Row row, Integer rowIndex, Head head, Integer columnIndex, Integer relativeRowIndex, Boolean isHead, ExcelContentProperty excelContentProperty) { return new CellWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(), writeContext.writeSheetHolder(), writeContext.writeTableHolder(), row, rowIndex, null, columnIndex, relativeRowIndex, head, null, null, isHead, excelContentProperty); } public static void beforeCellCreate(CellWriteHandlerContext context) { CellHandlerExecutionChain cellHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext() .currentWriteHolder()).getCellHandlerExecutionChain(); if (cellHandlerExecutionChain != null) { cellHandlerExecutionChain.beforeCellCreate(context); } } public static void afterCellCreate(CellWriteHandlerContext context) { CellHandlerExecutionChain cellHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext() .currentWriteHolder()).getCellHandlerExecutionChain(); if (cellHandlerExecutionChain != null) { cellHandlerExecutionChain.afterCellCreate(context); } } public static void afterCellDataConverted(CellWriteHandlerContext context) { CellHandlerExecutionChain cellHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext() .currentWriteHolder()).getCellHandlerExecutionChain(); if (cellHandlerExecutionChain != null) { cellHandlerExecutionChain.afterCellDataConverted(context); } } public static void afterCellDispose(CellWriteHandlerContext context) { CellHandlerExecutionChain cellHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext() .currentWriteHolder()).getCellHandlerExecutionChain(); if (cellHandlerExecutionChain != null) { cellHandlerExecutionChain.afterCellDispose(context); } } public static RowWriteHandlerContext createRowWriteHandlerContext(WriteContext writeContext, Integer rowIndex, Integer relativeRowIndex, Boolean isHead) { return new RowWriteHandlerContext(writeContext, writeContext.writeWorkbookHolder(), writeContext.writeSheetHolder(), writeContext.writeTableHolder(), rowIndex, null, relativeRowIndex, isHead); } public static void beforeRowCreate(RowWriteHandlerContext context) { RowHandlerExecutionChain rowHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext() .currentWriteHolder()).getRowHandlerExecutionChain(); if (rowHandlerExecutionChain != null) { rowHandlerExecutionChain.beforeRowCreate(context); } } public static void afterRowCreate(RowWriteHandlerContext context) { RowHandlerExecutionChain rowHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext() .currentWriteHolder()).getRowHandlerExecutionChain(); if (rowHandlerExecutionChain != null) { rowHandlerExecutionChain.afterRowCreate(context); } } public static void afterRowDispose(RowWriteHandlerContext context) { RowHandlerExecutionChain rowHandlerExecutionChain = ((AbstractWriteHolder)context.getWriteContext() .currentWriteHolder()).getRowHandlerExecutionChain(); if (rowHandlerExecutionChain != null) { rowHandlerExecutionChain.afterRowDispose(context); } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/Validate.java
easyexcel-core/src/main/java/com/alibaba/excel/util/Validate.java
package com.alibaba.excel.util; import java.util.Objects; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Apache Software Foundation (ASF) */ public class Validate { private static final String DEFAULT_IS_TRUE_EX_MESSAGE = "The validated expression is false"; private static final String DEFAULT_IS_NULL_EX_MESSAGE = "The validated object is null"; /** * <p>Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre>Validate.isTrue(i &gt; 0.0, "The value must be greater than zero: &#37;d", i);</pre> * * <p>For performance reasons, the long value is passed as a separate parameter and * appended to the exception message only in the case of an error.</p> * * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param value the value to append to the message when invalid * @throws IllegalArgumentException if expression is {@code false} * @see #isTrue(boolean) * @see #isTrue(boolean, String, double) * @see #isTrue(boolean, String, Object...) */ public static void isTrue(final boolean expression, final String message, final long value) { if (!expression) { throw new IllegalArgumentException(String.format(message, Long.valueOf(value))); } } /** * <p>Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre>Validate.isTrue(d &gt; 0.0, "The value must be greater than zero: &#37;s", d);</pre> * * <p>For performance reasons, the double value is passed as a separate parameter and * appended to the exception message only in the case of an error.</p> * * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param value the value to append to the message when invalid * @throws IllegalArgumentException if expression is {@code false} * @see #isTrue(boolean) * @see #isTrue(boolean, String, long) * @see #isTrue(boolean, String, Object...) */ public static void isTrue(final boolean expression, final String message, final double value) { if (!expression) { throw new IllegalArgumentException(String.format(message, Double.valueOf(value))); } } /** * <p>Validate that the argument condition is {@code true}; otherwise * throwing an exception with the specified message. This method is useful when * validating according to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre> * Validate.isTrue(i &gt;= min &amp;&amp; i &lt;= max, "The value must be between &#37;d and &#37;d", min, max); * Validate.isTrue(myObject.isOk(), "The object is not okay");</pre> * * @param expression the boolean expression to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message, null array not recommended * @throws IllegalArgumentException if expression is {@code false} * @see #isTrue(boolean) * @see #isTrue(boolean, String, long) * @see #isTrue(boolean, String, double) */ public static void isTrue(final boolean expression, final String message, final Object... values) { if (!expression) { throw new IllegalArgumentException(String.format(message, values)); } } /** * <p>Validate that the argument condition is {@code true}; otherwise * throwing an exception. This method is useful when validating according * to an arbitrary boolean expression, such as validating a * primitive number or using your own custom validation expression.</p> * * <pre> * Validate.isTrue(i &gt; 0); * Validate.isTrue(myObject.isOk());</pre> * * <p>The message of the exception is &quot;The validated expression is * false&quot;.</p> * * @param expression the boolean expression to check * @throws IllegalArgumentException if expression is {@code false} * @see #isTrue(boolean, String, long) * @see #isTrue(boolean, String, double) * @see #isTrue(boolean, String, Object...) */ public static void isTrue(final boolean expression) { if (!expression) { throw new IllegalArgumentException(DEFAULT_IS_TRUE_EX_MESSAGE); } } /** * <p>Validate that the specified argument is not {@code null}; * otherwise throwing an exception. * * <pre>Validate.notNull(myObject, "The object must not be null");</pre> * * <p>The message of the exception is &quot;The validated object is * null&quot;.</p> * * @param <T> the object type * @param object the object to check * @return the validated object (never {@code null} for method chaining) * @throws NullPointerException if the object is {@code null} * @see #notNull(Object, String, Object...) */ public static <T> T notNull(final T object) { return notNull(object, DEFAULT_IS_NULL_EX_MESSAGE); } /** * <p>Validate that the specified argument is not {@code null}; * otherwise throwing an exception with the specified message. * * <pre>Validate.notNull(myObject, "The object must not be null");</pre> * * @param <T> the object type * @param object the object to check * @param message the {@link String#format(String, Object...)} exception message if invalid, not null * @param values the optional values for the formatted exception message * @return the validated object (never {@code null} for method chaining) * @throws NullPointerException if the object is {@code null} * @see #notNull(Object) */ public static <T> T notNull(final T object, final String message, final Object... values) { return Objects.requireNonNull(object, () -> String.format(message, values)); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/IoUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/IoUtils.java
package com.alibaba.excel.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * IO Utils * * @author Jiaju Zhuang */ public class IoUtils { public static final int EOF = -1; /** * The default buffer size ({@value}) to use for */ private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; private IoUtils() {} /** * Gets the contents of an InputStream as a byte[]. * * @param input * @return * @throws IOException */ public static byte[] toByteArray(final InputStream input) throws IOException { final ByteArrayOutputStream output = new ByteArrayOutputStream(); try { copy(input, output); return output.toByteArray(); } finally { output.toByteArray(); } } /** * Gets the contents of an InputStream as a byte[]. * * @param input * @param size * @return * @throws IOException */ public static byte[] toByteArray(final InputStream input, final int size) throws IOException { if (size < 0) { throw new IllegalArgumentException("Size must be equal or greater than zero: " + size); } if (size == 0) { return new byte[0]; } final byte[] data = new byte[size]; int offset = 0; int read; while (offset < size && (read = input.read(data, offset, size - offset)) != EOF) { offset += read; } if (offset != size) { throw new IOException("Unexpected read size. current: " + offset + ", expected: " + size); } return data; } /** * Copies bytes * * @param input * @param output * @return * @throws IOException */ public static int copy(final InputStream input, final OutputStream output) throws IOException { long count = 0; int n; byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; while (EOF != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } if (count > Integer.MAX_VALUE) { return -1; } return (int)count; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/FileTypeUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/FileTypeUtils.java
package com.alibaba.excel.util; import java.util.HashMap; import java.util.Map; import com.alibaba.excel.metadata.data.ImageData.ImageType; /** * file type utils * * @author Jiaju Zhuang */ public class FileTypeUtils { private static final char[] DIGITS = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; private static final int IMAGE_TYPE_MARK_LENGTH = 28; private static final Map<String, ImageType> FILE_TYPE_MAP; /** * Default image type */ public static ImageType defaultImageType = ImageType.PICTURE_TYPE_PNG; static { FILE_TYPE_MAP = new HashMap<>(); FILE_TYPE_MAP.put("ffd8ff", ImageType.PICTURE_TYPE_JPEG); FILE_TYPE_MAP.put("89504e47", ImageType.PICTURE_TYPE_PNG); } public static int getImageTypeFormat(byte[] image) { ImageType imageType = getImageType(image); if (imageType != null) { return imageType.getValue(); } return defaultImageType.getValue(); } public static ImageType getImageType(byte[] image) { if (image == null || image.length <= IMAGE_TYPE_MARK_LENGTH) { return null; } byte[] typeMarkByte = new byte[IMAGE_TYPE_MARK_LENGTH]; System.arraycopy(image, 0, typeMarkByte, 0, IMAGE_TYPE_MARK_LENGTH); return FILE_TYPE_MAP.get(encodeHexStr(typeMarkByte)); } private static String encodeHexStr(byte[] data) { final int len = data.length; final char[] out = new char[len << 1]; // two characters from the hex value. for (int i = 0, j = 0; i < len; i++) { out[j++] = DIGITS[(0xF0 & data[i]) >>> 4]; out[j++] = DIGITS[0x0F & data[i]]; } return new String(out); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/IntUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/IntUtils.java
package com.alibaba.excel.util; /** * Int utils * * @author Jiaju Zhuang **/ public class IntUtils { private IntUtils() {} /** * The largest power of two that can be represented as an {@code int}. * * @since 10.0 */ public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); /** * Returns the {@code int} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code int} if it is in the range of the {@code int} type, * {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too * small */ public static int saturatedCast(long value) { if (value > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (value < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) value; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/EasyExcelTempFileCreationStrategy.java
easyexcel-core/src/main/java/com/alibaba/excel/util/EasyExcelTempFileCreationStrategy.java
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ package com.alibaba.excel.util; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.attribute.FileAttribute; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.apache.poi.util.DefaultTempFileCreationStrategy; import org.apache.poi.util.TempFileCreationStrategy; import static org.apache.poi.util.TempFile.JAVA_IO_TMPDIR; /** * In the scenario where `poifiles` are cleaned up, the {@link DefaultTempFileCreationStrategy} will throw a * java.nio.file.NoSuchFileException. Therefore, it is necessary to verify the existence of the temporary file every * time it is created. * * @author Jiaju Zhuang */ public class EasyExcelTempFileCreationStrategy implements TempFileCreationStrategy { /** * Name of POI files directory in temporary directory. */ public static final String POIFILES = "poifiles"; /** * To use files.deleteOnExit after clean JVM exit, set the <code>-Dpoi.delete.tmp.files.on.exit</code> JVM property */ public static final String DELETE_FILES_ON_EXIT = "poi.delete.tmp.files.on.exit"; /** * The directory where the temporary files will be created (<code>null</code> to use the default directory). */ private volatile File dir; /** * The lock to make dir initialized only once. */ private final Lock dirLock = new ReentrantLock(); /** * Creates the strategy so that it creates the temporary files in the default directory. * * @see File#createTempFile(String, String) */ public EasyExcelTempFileCreationStrategy() { this(null); } /** * Creates the strategy allowing to set the * * @param dir The directory where the temporary files will be created (<code>null</code> to use the default * directory). * @see Files#createTempFile(Path, String, String, FileAttribute[]) */ public EasyExcelTempFileCreationStrategy(File dir) { this.dir = dir; } private void createPOIFilesDirectory() throws IOException { // Create our temp dir only once by double-checked locking // The directory is not deleted, even if it was created by this TempFileCreationStrategy if (dir == null || !dir.exists()) { dirLock.lock(); try { if (dir == null || !dir.exists()) { String tmpDir = System.getProperty(JAVA_IO_TMPDIR); if (tmpDir == null) { throw new IOException("System's temporary directory not defined - set the -D" + JAVA_IO_TMPDIR + " jvm property!"); } Path dirPath = Paths.get(tmpDir, POIFILES); dir = Files.createDirectories(dirPath).toFile(); } } finally { dirLock.unlock(); } return; } } @Override public File createTempFile(String prefix, String suffix) throws IOException { // Identify and create our temp dir, if needed createPOIFilesDirectory(); // Generate a unique new filename File newFile = Files.createTempFile(dir.toPath(), prefix, suffix).toFile(); // Set the delete on exit flag, but only when explicitly disabled if (System.getProperty(DELETE_FILES_ON_EXIT) != null) { newFile.deleteOnExit(); } // All done return newFile; } /* (non-JavaDoc) Created directory path is <JAVA_IO_TMPDIR>/poifiles/prefix0123456789 */ @Override public File createTempDirectory(String prefix) throws IOException { // Identify and create our temp dir, if needed createPOIFilesDirectory(); // Generate a unique new filename File newDirectory = Files.createTempDirectory(dir.toPath(), prefix).toFile(); //this method appears to be only used in tests, so it is probably ok to use deleteOnExit newDirectory.deleteOnExit(); // All done return newDirectory; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/WorkBookUtil.java
easyexcel-core/src/main/java/com/alibaba/excel/util/WorkBookUtil.java
package com.alibaba.excel.util; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import com.alibaba.excel.metadata.csv.CsvWorkbook; import com.alibaba.excel.metadata.data.DataFormatData; import com.alibaba.excel.metadata.data.WriteCellData; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; import com.alibaba.excel.write.metadata.style.WriteCellStyle; import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.poifs.filesystem.POIFSFileSystem; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.streaming.SXSSFWorkbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; /** * @author jipengfei */ public class WorkBookUtil { private WorkBookUtil() {} public static void createWorkBook(WriteWorkbookHolder writeWorkbookHolder) throws IOException { switch (writeWorkbookHolder.getExcelType()) { case XLSX: if (writeWorkbookHolder.getTempTemplateInputStream() != null) { XSSFWorkbook xssfWorkbook = new XSSFWorkbook(writeWorkbookHolder.getTempTemplateInputStream()); writeWorkbookHolder.setCachedWorkbook(xssfWorkbook); if (writeWorkbookHolder.getInMemory()) { writeWorkbookHolder.setWorkbook(xssfWorkbook); } else { writeWorkbookHolder.setWorkbook(new SXSSFWorkbook(xssfWorkbook)); } return; } Workbook workbook; if (writeWorkbookHolder.getInMemory()) { workbook = new XSSFWorkbook(); } else { workbook = new SXSSFWorkbook(); } writeWorkbookHolder.setCachedWorkbook(workbook); writeWorkbookHolder.setWorkbook(workbook); return; case XLS: HSSFWorkbook hssfWorkbook; if (writeWorkbookHolder.getTempTemplateInputStream() != null) { hssfWorkbook = new HSSFWorkbook( new POIFSFileSystem(writeWorkbookHolder.getTempTemplateInputStream())); } else { hssfWorkbook = new HSSFWorkbook(); } writeWorkbookHolder.setCachedWorkbook(hssfWorkbook); writeWorkbookHolder.setWorkbook(hssfWorkbook); if (writeWorkbookHolder.getPassword() != null) { Biff8EncryptionKey.setCurrentUserPassword(writeWorkbookHolder.getPassword()); hssfWorkbook.writeProtectWorkbook(writeWorkbookHolder.getPassword(), StringUtils.EMPTY); } return; case CSV: CsvWorkbook csvWorkbook = new CsvWorkbook(new PrintWriter( new OutputStreamWriter(writeWorkbookHolder.getOutputStream(), writeWorkbookHolder.getCharset())), writeWorkbookHolder.getGlobalConfiguration().getLocale(), writeWorkbookHolder.getGlobalConfiguration().getUse1904windowing(), writeWorkbookHolder.getGlobalConfiguration().getUseScientificFormat(), writeWorkbookHolder.getCharset(), writeWorkbookHolder.getWithBom()); writeWorkbookHolder.setCachedWorkbook(csvWorkbook); writeWorkbookHolder.setWorkbook(csvWorkbook); return; default: throw new UnsupportedOperationException("Wrong excel type."); } } public static Sheet createSheet(Workbook workbook, String sheetName) { return workbook.createSheet(sheetName); } public static Row createRow(Sheet sheet, int rowNum) { return sheet.createRow(rowNum); } public static Cell createCell(Row row, int colNum) { return row.createCell(colNum); } public static Cell createCell(Row row, int colNum, CellStyle cellStyle) { Cell cell = row.createCell(colNum); cell.setCellStyle(cellStyle); return cell; } public static Cell createCell(Row row, int colNum, CellStyle cellStyle, String cellValue) { Cell cell = createCell(row, colNum, cellStyle); cell.setCellValue(cellValue); return cell; } public static Cell createCell(Row row, int colNum, String cellValue) { Cell cell = row.createCell(colNum); cell.setCellValue(cellValue); return cell; } public static void fillDataFormat(WriteCellData<?> cellData, String format, String defaultFormat) { if (cellData.getWriteCellStyle() == null) { cellData.setWriteCellStyle(new WriteCellStyle()); } if (cellData.getWriteCellStyle().getDataFormatData() == null) { cellData.getWriteCellStyle().setDataFormatData(new DataFormatData()); } if (cellData.getWriteCellStyle().getDataFormatData().getFormat() == null) { if (format == null) { cellData.getWriteCellStyle().getDataFormatData().setFormat(defaultFormat); } else { cellData.getWriteCellStyle().getDataFormatData().setFormat(format); } } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/MapUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/MapUtils.java
package com.alibaba.excel.util; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.TreeMap; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Apache Software Foundation (ASF) */ public class MapUtils { private MapUtils() {} /** * Creates a <i>mutable</i>, empty {@code HashMap} instance. * * <p><b>Note:</b> if mutability is not required, use ImmutableMap.of() instead. * * <p><b>Note:</b> if {@code K} is an {@code enum} type, use newEnumMap instead. * * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as * deprecated. Instead, use the {@code HashMap} constructor directly, taking advantage of the new * <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @return a new, empty {@code HashMap} */ public static <K, V> HashMap<K, V> newHashMap() { return new HashMap<>(16); } /** * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural ordering of its * elements. * * <p><b>Note:</b> if mutability is not required, use ImmutableSortedMap.of() instead. * * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as * deprecated. Instead, use the {@code TreeMap} constructor directly, taking advantage of the new * <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @return a new, empty {@code TreeMap} */ public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() { return new TreeMap<>(); } /** * Creates a {@code HashMap} instance, with a high enough "initial capacity" that it <i>should</i> * hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed, * but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method * isn't inadvertently <i>oversizing</i> the returned map. * * @param expectedSize the number of entries you expect to add to the returned map * @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries * without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative */ public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) { return new HashMap<>(capacity(expectedSize)); } /** * Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} instance. * * <p><b>Note:</b> if mutability is not required, use ImmutableMap.of() instead. * * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as * deprecated. Instead, use the {@code LinkedHashMap} constructor directly, taking advantage of * the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @return a new, empty {@code LinkedHashMap} */ public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() { return new LinkedHashMap<>(); } /** * Creates a {@code LinkedHashMap} instance, with a high enough "initial capacity" that it * <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be * broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed * that the method isn't inadvertently <i>oversizing</i> the returned map. * * @param expectedSize the number of entries you expect to add to the returned map * @return a new, empty {@code LinkedHashMap} with enough capacity to hold {@code expectedSize} * entries without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative * @since 19.0 */ public static <K, V> LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) { return new LinkedHashMap<>(capacity(expectedSize)); } /** * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no * larger than expectedSize and the load factor is ≥ its default (0.75). */ static int capacity(int expectedSize) { if (expectedSize < 3) { return expectedSize + 1; } if (expectedSize < IntUtils.MAX_POWER_OF_TWO) { // This is the calculation used in JDK8 to resize when a putAll // happens; it seems to be the most conservative calculation we // can make. 0.75 is the default load factor. return (int)((float)expectedSize / 0.75F + 1.0F); } return Integer.MAX_VALUE; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/StyleUtil.java
easyexcel-core/src/main/java/com/alibaba/excel/util/StyleUtil.java
package com.alibaba.excel.util; import java.util.Optional; import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.metadata.data.DataFormatData; import com.alibaba.excel.metadata.data.HyperlinkData; import com.alibaba.excel.metadata.data.RichTextStringData; import com.alibaba.excel.metadata.data.RichTextStringData.IntervalFont; import com.alibaba.excel.support.ExcelTypeEnum; import com.alibaba.excel.write.metadata.holder.WriteWorkbookHolder; import com.alibaba.excel.write.metadata.style.WriteCellStyle; import com.alibaba.excel.write.metadata.style.WriteFont; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.apache.poi.common.usermodel.HyperlinkType; import org.apache.poi.hssf.usermodel.HSSFFont; import org.apache.poi.hssf.usermodel.HSSFRichTextString; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.util.Units; import org.apache.poi.xssf.usermodel.XSSFColor; import org.apache.poi.xssf.usermodel.XSSFFont; import org.apache.poi.xssf.usermodel.XSSFRichTextString; /** * @author jipengfei */ @Slf4j public class StyleUtil { private StyleUtil() {} /** * Build cell style * * @param workbook * @param originCellStyle * @param writeCellStyle * @return */ public static CellStyle buildCellStyle(Workbook workbook, CellStyle originCellStyle, WriteCellStyle writeCellStyle) { CellStyle cellStyle = workbook.createCellStyle(); if (originCellStyle != null) { cellStyle.cloneStyleFrom(originCellStyle); } if (writeCellStyle == null) { return cellStyle; } buildCellStyle(cellStyle, writeCellStyle); return cellStyle; } private static void buildCellStyle(CellStyle cellStyle, WriteCellStyle writeCellStyle) { if (writeCellStyle.getHidden() != null) { cellStyle.setHidden(writeCellStyle.getHidden()); } if (writeCellStyle.getLocked() != null) { cellStyle.setLocked(writeCellStyle.getLocked()); } if (writeCellStyle.getQuotePrefix() != null) { cellStyle.setQuotePrefixed(writeCellStyle.getQuotePrefix()); } if (writeCellStyle.getHorizontalAlignment() != null) { cellStyle.setAlignment(writeCellStyle.getHorizontalAlignment()); } if (writeCellStyle.getWrapped() != null) { cellStyle.setWrapText(writeCellStyle.getWrapped()); } if (writeCellStyle.getVerticalAlignment() != null) { cellStyle.setVerticalAlignment(writeCellStyle.getVerticalAlignment()); } if (writeCellStyle.getRotation() != null) { cellStyle.setRotation(writeCellStyle.getRotation()); } if (writeCellStyle.getIndent() != null) { cellStyle.setIndention(writeCellStyle.getIndent()); } if (writeCellStyle.getBorderLeft() != null) { cellStyle.setBorderLeft(writeCellStyle.getBorderLeft()); } if (writeCellStyle.getBorderRight() != null) { cellStyle.setBorderRight(writeCellStyle.getBorderRight()); } if (writeCellStyle.getBorderTop() != null) { cellStyle.setBorderTop(writeCellStyle.getBorderTop()); } if (writeCellStyle.getBorderBottom() != null) { cellStyle.setBorderBottom(writeCellStyle.getBorderBottom()); } if (writeCellStyle.getLeftBorderColor() != null) { cellStyle.setLeftBorderColor(writeCellStyle.getLeftBorderColor()); } if (writeCellStyle.getRightBorderColor() != null) { cellStyle.setRightBorderColor(writeCellStyle.getRightBorderColor()); } if (writeCellStyle.getTopBorderColor() != null) { cellStyle.setTopBorderColor(writeCellStyle.getTopBorderColor()); } if (writeCellStyle.getBottomBorderColor() != null) { cellStyle.setBottomBorderColor(writeCellStyle.getBottomBorderColor()); } if (writeCellStyle.getFillPatternType() != null) { cellStyle.setFillPattern(writeCellStyle.getFillPatternType()); } if (writeCellStyle.getFillBackgroundColor() != null) { cellStyle.setFillBackgroundColor(writeCellStyle.getFillBackgroundColor()); } if (writeCellStyle.getFillForegroundColor() != null) { cellStyle.setFillForegroundColor(writeCellStyle.getFillForegroundColor()); } if (writeCellStyle.getShrinkToFit() != null) { cellStyle.setShrinkToFit(writeCellStyle.getShrinkToFit()); } } public static short buildDataFormat(Workbook workbook, DataFormatData dataFormatData) { if (dataFormatData == null) { return BuiltinFormats.GENERAL; } if (dataFormatData.getIndex() != null && dataFormatData.getIndex() >= 0) { return dataFormatData.getIndex(); } if (StringUtils.isNotBlank(dataFormatData.getFormat())) { if (log.isDebugEnabled()) { log.info("create new data fromat:{}", dataFormatData); } DataFormat dataFormatCreate = workbook.createDataFormat(); return dataFormatCreate.getFormat(dataFormatData.getFormat()); } return BuiltinFormats.GENERAL; } public static Font buildFont(Workbook workbook, Font originFont, WriteFont writeFont) { if (log.isDebugEnabled()) { log.info("create new font:{},{}", writeFont, originFont); } if (writeFont == null && originFont == null) { return null; } Font font = createFont(workbook, originFont, writeFont); if (writeFont == null || font == null) { return font; } if (writeFont.getFontName() != null) { font.setFontName(writeFont.getFontName()); } if (writeFont.getFontHeightInPoints() != null) { font.setFontHeightInPoints(writeFont.getFontHeightInPoints()); } if (writeFont.getItalic() != null) { font.setItalic(writeFont.getItalic()); } if (writeFont.getStrikeout() != null) { font.setStrikeout(writeFont.getStrikeout()); } if (writeFont.getColor() != null) { font.setColor(writeFont.getColor()); } if (writeFont.getTypeOffset() != null) { font.setTypeOffset(writeFont.getTypeOffset()); } if (writeFont.getUnderline() != null) { font.setUnderline(writeFont.getUnderline()); } if (writeFont.getCharset() != null) { font.setCharSet(writeFont.getCharset()); } if (writeFont.getBold() != null) { font.setBold(writeFont.getBold()); } return font; } private static Font createFont(Workbook workbook, Font originFont, WriteFont writeFont) { Font font = workbook.createFont(); if (originFont == null) { return font; } if (originFont instanceof XSSFFont) { XSSFFont xssfFont = (XSSFFont)font; XSSFFont xssfOriginFont = ((XSSFFont)originFont); xssfFont.setFontName(xssfOriginFont.getFontName()); xssfFont.setFontHeightInPoints(xssfOriginFont.getFontHeightInPoints()); xssfFont.setItalic(xssfOriginFont.getItalic()); xssfFont.setStrikeout(xssfOriginFont.getStrikeout()); // Colors cannot be overwritten if (writeFont == null || writeFont.getColor() == null) { xssfFont.setColor(Optional.of(xssfOriginFont) .map(XSSFFont::getXSSFColor) .map(XSSFColor::getRGB) .map(rgb -> new XSSFColor(rgb, null)) .orElse(null)); } xssfFont.setTypeOffset(xssfOriginFont.getTypeOffset()); xssfFont.setUnderline(xssfOriginFont.getUnderline()); xssfFont.setCharSet(xssfOriginFont.getCharSet()); xssfFont.setBold(xssfOriginFont.getBold()); return xssfFont; } else if (originFont instanceof HSSFFont) { HSSFFont hssfFont = (HSSFFont)font; HSSFFont hssfOriginFont = (HSSFFont)originFont; hssfFont.setFontName(hssfOriginFont.getFontName()); hssfFont.setFontHeightInPoints(hssfOriginFont.getFontHeightInPoints()); hssfFont.setItalic(hssfOriginFont.getItalic()); hssfFont.setStrikeout(hssfOriginFont.getStrikeout()); hssfFont.setColor(hssfOriginFont.getColor()); hssfFont.setTypeOffset(hssfOriginFont.getTypeOffset()); hssfFont.setUnderline(hssfOriginFont.getUnderline()); hssfFont.setCharSet(hssfOriginFont.getCharSet()); hssfFont.setBold(hssfOriginFont.getBold()); return hssfFont; } return font; } public static RichTextString buildRichTextString(WriteWorkbookHolder writeWorkbookHolder, RichTextStringData richTextStringData) { if (richTextStringData == null) { return null; } RichTextString richTextString; if (writeWorkbookHolder.getExcelType() == ExcelTypeEnum.XLSX) { richTextString = new XSSFRichTextString(richTextStringData.getTextString()); } else { richTextString = new HSSFRichTextString(richTextStringData.getTextString()); } if (richTextStringData.getWriteFont() != null) { richTextString.applyFont(writeWorkbookHolder.createFont(richTextStringData.getWriteFont(), null, true)); } if (CollectionUtils.isNotEmpty(richTextStringData.getIntervalFontList())) { for (IntervalFont intervalFont : richTextStringData.getIntervalFontList()) { richTextString.applyFont(intervalFont.getStartIndex(), intervalFont.getEndIndex(), writeWorkbookHolder.createFont(intervalFont.getWriteFont(), null, true)); } } return richTextString; } public static HyperlinkType getHyperlinkType(HyperlinkData.HyperlinkType hyperlinkType) { if (hyperlinkType == null) { return HyperlinkType.NONE; } return hyperlinkType.getValue(); } public static int getCoordinate(Integer coordinate) { if (coordinate == null) { return 0; } return Units.toEMU(coordinate); } public static int getCellCoordinate(Integer currentCoordinate, Integer absoluteCoordinate, Integer relativeCoordinate) { if (absoluteCoordinate != null && absoluteCoordinate > 0) { return absoluteCoordinate; } if (relativeCoordinate != null) { return currentCoordinate + relativeCoordinate; } return currentCoordinate; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/PoiUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/PoiUtils.java
package com.alibaba.excel.util; import com.alibaba.excel.exception.ExcelRuntimeException; import org.apache.poi.hssf.record.RowRecord; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.util.BitField; import org.apache.poi.util.BitFieldFactory; import org.apache.poi.xssf.usermodel.XSSFRow; import java.lang.reflect.Field; /** * utils * * @author Jiaju Zhuang */ public class PoiUtils { /** * Whether to customize the height */ public static final BitField CUSTOM_HEIGHT = BitFieldFactory.getInstance(0x640); private static final Field ROW_RECORD_FIELD = FieldUtils.getField(HSSFRow.class, "row", true); /** * Whether to customize the height * * @param row row * @return */ public static boolean customHeight(Row row) { if (row instanceof XSSFRow) { XSSFRow xssfRow = (XSSFRow)row; return xssfRow.getCTRow().getCustomHeight(); } if (row instanceof HSSFRow) { HSSFRow hssfRow = (HSSFRow)row; try { RowRecord record = (RowRecord)ROW_RECORD_FIELD.get(hssfRow); return CUSTOM_HEIGHT.getValue(record.getOptionFlags()) == 1; } catch (IllegalAccessException ignore) { } } return false; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/PositionUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/PositionUtils.java
package com.alibaba.excel.util; import java.util.regex.Pattern; /** * @author jipengfei */ public class PositionUtils { private static final Pattern CELL_REF_PATTERN = Pattern.compile("(\\$?[A-Z]+)?" + "(\\$?[0-9]+)?", Pattern.CASE_INSENSITIVE); private static final char SHEET_NAME_DELIMITER = '!'; private static final char REDUNDANT_CHARACTERS = '$'; private PositionUtils() {} public static int getRowByRowTagt(String rowTagt, Integer before) { int row; if (rowTagt != null) { row = Integer.parseInt(rowTagt) - 1; return row; } else { if (before == null) { before = -1; } return before + 1; } } public static int getRow(String currentCellIndex) { if (currentCellIndex == null) { return -1; } int firstNumber = currentCellIndex.length() - 1; for (; firstNumber >= 0; firstNumber--) { char c = currentCellIndex.charAt(firstNumber); if (c < '0' || c > '9') { break; } } return Integer.parseUnsignedInt(currentCellIndex.substring(firstNumber + 1)) - 1; } public static int getCol(String currentCellIndex, Integer before) { if (currentCellIndex == null) { if (before == null) { before = -1; } return before + 1; } int firstNumber = currentCellIndex.charAt(0) == REDUNDANT_CHARACTERS ? 1 : 0; int col = 0; for (; firstNumber < currentCellIndex.length(); firstNumber++) { char c = currentCellIndex.charAt(firstNumber); boolean isNotLetter = c == REDUNDANT_CHARACTERS || (c >= '0' && c <= '9'); if (isNotLetter) { break; } col = col * 26 + Character.toUpperCase(c) - 'A' + 1; } return col - 1; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/BooleanUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/BooleanUtils.java
package com.alibaba.excel.util; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Apache Software Foundation (ASF) */ public class BooleanUtils { private static final String TRUE_NUMBER = "1"; private BooleanUtils() {} /** * String to boolean * * @param str * @return */ public static Boolean valueOf(String str) { if (TRUE_NUMBER.equals(str)) { return Boolean.TRUE; } else { return Boolean.FALSE; } } // boolean Boolean methods //----------------------------------------------------------------------- /** * <p>Checks if a {@code Boolean} value is {@code true}, * handling {@code null} by returning {@code false}.</p> * * <pre> * BooleanUtils.isTrue(Boolean.TRUE) = true * BooleanUtils.isTrue(Boolean.FALSE) = false * BooleanUtils.isTrue(null) = false * </pre> * * @param bool the boolean to check, null returns {@code false} * @return {@code true} only if the input is non-null and true * @since 2.1 */ public static boolean isTrue(final Boolean bool) { return Boolean.TRUE.equals(bool); } /** * <p>Checks if a {@code Boolean} value is <i>not</i> {@code true}, * handling {@code null} by returning {@code true}.</p> * * <pre> * BooleanUtils.isNotTrue(Boolean.TRUE) = false * BooleanUtils.isNotTrue(Boolean.FALSE) = true * BooleanUtils.isNotTrue(null) = true * </pre> * * @param bool the boolean to check, null returns {@code true} * @return {@code true} if the input is null or false * @since 2.3 */ public static boolean isNotTrue(final Boolean bool) { return !isTrue(bool); } /** * <p>Checks if a {@code Boolean} value is {@code false}, * handling {@code null} by returning {@code false}.</p> * * <pre> * BooleanUtils.isFalse(Boolean.TRUE) = false * BooleanUtils.isFalse(Boolean.FALSE) = true * BooleanUtils.isFalse(null) = false * </pre> * * @param bool the boolean to check, null returns {@code false} * @return {@code true} only if the input is non-null and false * @since 2.1 */ public static boolean isFalse(final Boolean bool) { return Boolean.FALSE.equals(bool); } /** * <p>Checks if a {@code Boolean} value is <i>not</i> {@code false}, * handling {@code null} by returning {@code true}.</p> * * <pre> * BooleanUtils.isNotFalse(Boolean.TRUE) = true * BooleanUtils.isNotFalse(Boolean.FALSE) = false * BooleanUtils.isNotFalse(null) = true * </pre> * * @param bool the boolean to check, null returns {@code true} * @return {@code true} if the input is null or true * @since 2.3 */ public static boolean isNotFalse(final Boolean bool) { return !isFalse(bool); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/ListUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/ListUtils.java
package com.alibaba.excel.util; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import lombok.NonNull; import org.apache.commons.compress.utils.Iterators; /** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * @author Apache Software Foundation (ASF) */ public class ListUtils { private ListUtils() {} /** * Creates a <i>mutable</i>, empty {@code ArrayList} instance (for Java 6 and earlier). * * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as * deprecated. Instead, use the {@code ArrayList} {@linkplain ArrayList#ArrayList() constructor} * directly, taking advantage of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. */ public static <E> ArrayList<E> newArrayList() { return new ArrayList<>(); } /** * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements. * */ public static <E> ArrayList<E> newArrayList(E... elements) { checkNotNull(elements); // Avoid integer overflow when a large array is passed in int capacity = computeArrayListCapacity(elements.length); ArrayList<E> list = new ArrayList<>(capacity); Collections.addAll(list, elements); return list; } /** * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin * shortcut for creating an empty list and then calling {@link Iterators#addAll}. * */ public static <E> ArrayList<E> newArrayList(Iterator<? extends E> elements) { ArrayList<E> list = newArrayList(); Iterators.addAll(list, elements); return list; } /** * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; * * * <p><b>Note for Java 7 and later:</b> if {@code elements} is a {@link Collection}, you don't * need this method. Use the {@code ArrayList} {@linkplain ArrayList#ArrayList(Collection) * constructor} directly, taking advantage of the new <a href="http://goo.gl/iz2Wi">"diamond" * syntax</a>. */ public static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) { checkNotNull(elements); // for GWT // Let ArrayList's sizing logic work, if possible return (elements instanceof Collection) ? new ArrayList<>((Collection<? extends E>)elements) : newArrayList(elements.iterator()); } /** * Creates an {@code ArrayList} instance backed by an array with the specified initial size; * simply delegates to {@link ArrayList#ArrayList(int)}. * * <p><b>Note for Java 7 and later:</b> this method is now unnecessary and should be treated as * deprecated. Instead, use {@code new }{@link ArrayList#ArrayList(int) ArrayList}{@code <>(int)} * directly, taking advantage of the new <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * (Unlike here, there is no risk of overload ambiguity, since the {@code ArrayList} constructors * very wisely did not accept varargs.) * * @param initialArraySize the exact size of the initial backing array for the returned array list * ({@code ArrayList} documentation calls this value the "capacity") * @return a new, empty {@code ArrayList} which is guaranteed not to resize itself unless its size * reaches {@code initialArraySize + 1} * @throws IllegalArgumentException if {@code initialArraySize} is negative */ public static <E> ArrayList<E> newArrayListWithCapacity(int initialArraySize) { checkNonnegative(initialArraySize, "initialArraySize"); return new ArrayList<>(initialArraySize); } /** * Creates an {@code ArrayList} instance to hold {@code estimatedSize} elements, <i>plus</i> an * unspecified amount of padding; you almost certainly mean to call {@link * #newArrayListWithCapacity} (see that method for further advice on usage). * * <p><b>Note:</b> This method will soon be deprecated. Even in the rare case that you do want * some amount of padding, it's best if you choose your desired amount explicitly. * * @param estimatedSize an estimate of the eventual {@link List#size()} of the new list * @return a new, empty {@code ArrayList}, sized appropriately to hold the estimated number of * elements * @throws IllegalArgumentException if {@code estimatedSize} is negative */ public static <E> ArrayList<E> newArrayListWithExpectedSize(int estimatedSize) { return new ArrayList<>(computeArrayListCapacity(estimatedSize)); } static int computeArrayListCapacity(int arraySize) { checkNonnegative(arraySize, "arraySize"); return IntUtils.saturatedCast(5L + arraySize + (arraySize / 10)); } static int checkNonnegative(int value, String name) { if (value < 0) { throw new IllegalArgumentException(name + " cannot be negative but was: " + value); } return value; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T extends @NonNull Object> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java
easyexcel-core/src/main/java/com/alibaba/excel/util/NumberDataFormatterUtils.java
package com.alibaba.excel.util; import java.math.BigDecimal; import java.util.Locale; import com.alibaba.excel.metadata.GlobalConfiguration; import com.alibaba.excel.metadata.format.DataFormatter; /** * Convert number data, including date. * * @author Jiaju Zhuang **/ public class NumberDataFormatterUtils { /** * Cache DataFormatter. */ private static final ThreadLocal<DataFormatter> DATA_FORMATTER_THREAD_LOCAL = new ThreadLocal<DataFormatter>(); /** * Format number data. * * @param data * @param dataFormat Not null. * @param dataFormatString * @param globalConfiguration * @return */ public static String format(BigDecimal data, Short dataFormat, String dataFormatString, GlobalConfiguration globalConfiguration) { if (globalConfiguration == null) { return format(data, dataFormat, dataFormatString, null, null, null); } return format(data, dataFormat, dataFormatString, globalConfiguration.getUse1904windowing(), globalConfiguration.getLocale(), globalConfiguration.getUseScientificFormat()); } /** * Format number data. * * @param data * @param dataFormat Not null. * @param dataFormatString * @param use1904windowing * @param locale * @param useScientificFormat * @return */ public static String format(BigDecimal data, Short dataFormat, String dataFormatString, Boolean use1904windowing, Locale locale, Boolean useScientificFormat) { DataFormatter dataFormatter = DATA_FORMATTER_THREAD_LOCAL.get(); if (dataFormatter == null) { dataFormatter = new DataFormatter(use1904windowing, locale, useScientificFormat); DATA_FORMATTER_THREAD_LOCAL.set(dataFormatter); } return dataFormatter.format(data, dataFormat, dataFormatString); } public static void removeThreadLocalCache() { DATA_FORMATTER_THREAD_LOCAL.remove(); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/constant/OrderConstant.java
easyexcel-core/src/main/java/com/alibaba/excel/constant/OrderConstant.java
package com.alibaba.excel.constant; /** * Order constant. * * @author Jiaju Zhuang */ public class OrderConstant { /** * The system's own style */ public static int DEFAULT_DEFINE_STYLE = -70000; /** * Annotation style definition */ public static int ANNOTATION_DEFINE_STYLE = -60000; /** * Define style. */ public static final int DEFINE_STYLE = -50000; /** * default order. */ public static int DEFAULT_ORDER = 0; /** * Sorting of styles written to cells. */ public static int FILL_STYLE = 50000; }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java
easyexcel-core/src/main/java/com/alibaba/excel/constant/BuiltinFormats.java
package com.alibaba.excel.constant; import java.util.Locale; import java.util.Map; import com.alibaba.excel.util.MapUtils; import com.alibaba.excel.util.StringUtils; /** * Excel's built-in format conversion.Currently only supports Chinese. * * <p> * If it is not Chinese, it is recommended to directly modify the builtinFormats, which will better support * internationalization in the future. * * <p> * Specific correspondence please see: * https://docs.microsoft.com/en-us/dotnet/api/documentformat.openxml.spreadsheet.numberingformat?view=openxml-2.8.1 * * @author Jiaju Zhuang **/ public class BuiltinFormats { private static final String RESERVED = "reserved-"; public static short GENERAL = 0; public static final String[] BUILTIN_FORMATS_ALL_LANGUAGES = { // 0 "General", // 1 "0", // 2 "0.00", // 3 "#,##0", // 4 "#,##0.00", // 5 "\"¥\"#,##0_);(\"¥\"#,##0)", // 6 "\"¥\"#,##0_);[Red](\"¥\"#,##0)", // 7 "\"¥\"#,##0.00_);(\"¥\"#,##0.00)", // 8 "\"¥\"#,##0.00_);[Red](\"¥\"#,##0.00)", // 9 "0%", // 10 "0.00%", // 11 "0.00E+00", // 12 "# ?/?", // 13 "# ??/??", // 14 // The official documentation shows "m/d/yy", but the actual test is "yyyy/m/d". "yyyy/m/d", // 15 "d-mmm-yy", // 16 "d-mmm", // 17 "mmm-yy", // 18 "h:mm AM/PM", // 19 "h:mm:ss AM/PM", // 20 "h:mm", // 21 "h:mm:ss", // 22 // The official documentation shows "m/d/yy h:mm", but the actual test is "yyyy-m-d h:mm". "yyyy-m-d h:mm", // 23-36 No specific correspondence found in the official documentation. // 23 null, // 24 null, // 25 null, // 26 null, // 27 null, // 28 null, // 29 null, // 30 null, // 31 null, // 32 null, // 33 null, // 34 null, // 35 null, // 36 null, // 37 "#,##0_);(#,##0)", // 38 "#,##0_);[Red](#,##0)", // 39 "#,##0.00_);(#,##0.00)", // 40 "#,##0.00_);[Red](#,##0.00)", // 41 "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)", // 42 "_(\"¥\"* #,##0_);_(\"¥\"* (#,##0);_(\"¥\"* \"-\"_);_(@_)", // 43 "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)", // 44 "_(\"¥\"* #,##0.00_);_(\"¥\"* (#,##0.00);_(\"¥\"* \"-\"??_);_(@_)", // 45 "mm:ss", // 46 "[h]:mm:ss", // 47 "mm:ss.0", // 48 "##0.0E+0", // 49 "@", }; public static final String[] BUILTIN_FORMATS_CN = { // 0 "General", // 1 "0", // 2 "0.00", // 3 "#,##0", // 4 "#,##0.00", // 5 "\"¥\"#,##0_);(\"¥\"#,##0)", // 6 "\"¥\"#,##0_);[Red](\"¥\"#,##0)", // 7 "\"¥\"#,##0.00_);(\"¥\"#,##0.00)", // 8 "\"¥\"#,##0.00_);[Red](\"¥\"#,##0.00)", // 9 "0%", // 10 "0.00%", // 11 "0.00E+00", // 12 "# ?/?", // 13 "# ??/??", // 14 // The official documentation shows "m/d/yy", but the actual test is "yyyy/m/d". "yyyy/m/d", // 15 "d-mmm-yy", // 16 "d-mmm", // 17 "mmm-yy", // 18 "h:mm AM/PM", // 19 "h:mm:ss AM/PM", // 20 "h:mm", // 21 "h:mm:ss", // 22 // The official documentation shows "m/d/yy h:mm", but the actual test is "yyyy-m-d h:mm". "yyyy-m-d h:mm", // 23-26 No specific correspondence found in the official documentation. // 23 null, // 24 null, // 25 null, // 26 null, // 27 "yyyy\"年\"m\"月\"", // 28 "m\"月\"d\"日\"", // 29 "m\"月\"d\"日\"", // 30 "m-d-yy", // 31 "yyyy\"年\"m\"月\"d\"日\"", // 32 "h\"时\"mm\"分\"", // 33 "h\"时\"mm\"分\"ss\"秒\"", // 34 "上午/下午h\"时\"mm\"分\"", // 35 "上午/下午h\"时\"mm\"分\"ss\"秒\"", // 36 "yyyy\"年\"m\"月\"", // 37 "#,##0_);(#,##0)", // 38 "#,##0_);[Red](#,##0)", // 39 "#,##0.00_);(#,##0.00)", // 40 "#,##0.00_);[Red](#,##0.00)", // 41 "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)", // 42 "_(\"¥\"* #,##0_);_(\"¥\"* (#,##0);_(\"¥\"* \"-\"_);_(@_)", // 43 "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)", // 44 "_(\"¥\"* #,##0.00_);_(\"¥\"* (#,##0.00);_(\"¥\"* \"-\"??_);_(@_)", // 45 "mm:ss", // 46 "[h]:mm:ss", // 47 "mm:ss.0", // 48 "##0.0E+0", // 49 "@", // 50 "yyyy\"年\"m\"月\"", // 51 "m\"月\"d\"日\"", // 52 "yyyy\"年\"m\"月\"", // 53 "m\"月\"d\"日\"", // 54 "m\"月\"d\"日\"", // 55 "上午/下午h\"时\"mm\"分\"", // 56 "上午/下午h\"时\"mm\"分\"ss\"秒\"", // 57 "yyyy\"年\"m\"月\"", // 58 "m\"月\"d\"日\"", // 59 "t0", // 60 "t0.00", // 61 "t#,##0", // 62 "t#,##0.00", // 63-66 No specific correspondence found in the official documentation. // 63 null, // 64 null, // 65 null, // 66 null, // 67 "t0%", // 68 "t0.00%", // 69 "t# ?/?", // 70 "t# ??/??", // 71 "ว/ด/ปปปป", // 72 "ว-ดดด-ปป", // 73 "ว-ดดด", // 74 "ดดด-ปป", // 75 "ช:นน", // 76 "ช:นน:ทท", // 77 "ว/ด/ปปปป ช:นน", // 78 "นน:ทท", // 79 "[ช]:นน:ทท", // 80 "นน:ทท.0", // 81 "d/m/bb", // end }; public static final String[] BUILTIN_FORMATS_US = { // 0 "General", // 1 "0", // 2 "0.00", // 3 "#,##0", // 4 "#,##0.00", // 5 "\"$\"#,##0_);(\"$\"#,##0)", // 6 "\"$\"#,##0_);[Red](\"$\"#,##0)", // 7 "\"$\"#,##0.00_);(\"$\"#,##0.00)", // 8 "\"$\"#,##0.00_);[Red](\"$\"#,##0.00)", // 9 "0%", // 10 "0.00%", // 11 "0.00E+00", // 12 "# ?/?", // 13 "# ??/??", // 14 // The official documentation shows "m/d/yy", but the actual test is "yyyy/m/d". "yyyy/m/d", // 15 "d-mmm-yy", // 16 "d-mmm", // 17 "mmm-yy", // 18 "h:mm AM/PM", // 19 "h:mm:ss AM/PM", // 20 "h:mm", // 21 "h:mm:ss", // 22 // The official documentation shows "m/d/yy h:mm", but the actual test is "yyyy-m-d h:mm". "yyyy-m-d h:mm", // 23-26 No specific correspondence found in the official documentation. // 23 null, // 24 null, // 25 null, // 26 null, // 27 "yyyy\"年\"m\"月\"", // 28 "m\"月\"d\"日\"", // 29 "m\"月\"d\"日\"", // 30 "m-d-yy", // 31 "yyyy\"年\"m\"月\"d\"日\"", // 32 "h\"时\"mm\"分\"", // 33 "h\"时\"mm\"分\"ss\"秒\"", // 34 "上午/下午h\"时\"mm\"分\"", // 35 "上午/下午h\"时\"mm\"分\"ss\"秒\"", // 36 "yyyy\"年\"m\"月\"", // 37 "#,##0_);(#,##0)", // 38 "#,##0_);[Red](#,##0)", // 39 "#,##0.00_);(#,##0.00)", // 40 "#,##0.00_);[Red](#,##0.00)", // 41 "_(* #,##0_);_(* (#,##0);_(* \"-\"_);_(@_)", // 42 "_(\"$\"* #,##0_);_(\"$\"* (#,##0);_(\"$\"* \"-\"_);_(@_)", // 43 "_(* #,##0.00_);_(* (#,##0.00);_(* \"-\"??_);_(@_)", // 44 "_(\"$\"* #,##0.00_);_(\"$\"* (#,##0.00);_(\"$\"* \"-\"??_);_(@_)", // 45 "mm:ss", // 46 "[h]:mm:ss", // 47 "mm:ss.0", // 48 "##0.0E+0", // 49 "@", // 50 "yyyy\"年\"m\"月\"", // 51 "m\"月\"d\"日\"", // 52 "yyyy\"年\"m\"月\"", // 53 "m\"月\"d\"日\"", // 54 "m\"月\"d\"日\"", // 55 "上午/下午h\"时\"mm\"分\"", // 56 "上午/下午h\"时\"mm\"分\"ss\"秒\"", // 57 "yyyy\"年\"m\"月\"", // 58 "m\"月\"d\"日\"", // 59 "t0", // 60 "t0.00", // 61 "t#,##0", // 62 "t#,##0.00", // 63-66 No specific correspondence found in the official documentation. // 63 null, // 64 null, // 65 null, // 66 null, // 67 "t0%", // 68 "t0.00%", // 69 "t# ?/?", // 70 "t# ??/??", // 71 "ว/ด/ปปปป", // 72 "ว-ดดด-ปป", // 73 "ว-ดดด", // 74 "ดดด-ปป", // 75 "ช:นน", // 76 "ช:นน:ทท", // 77 "ว/ด/ปปปป ช:นน", // 78 "นน:ทท", // 79 "[ช]:นน:ทท", // 80 "นน:ทท.0", // 81 "d/m/bb", // end }; public static final Map<String, Short> BUILTIN_FORMATS_MAP_CN = buildMap(BUILTIN_FORMATS_CN); public static final Map<String, Short> BUILTIN_FORMATS_MAP_US = buildMap(BUILTIN_FORMATS_US); public static final short MIN_CUSTOM_DATA_FORMAT_INDEX = 82; public static String getBuiltinFormat(Short index, String defaultFormat, Locale locale) { if (index == null || index <= 0) { return defaultFormat; } // Give priority to checking if it is the default value for all languages if (index < BUILTIN_FORMATS_ALL_LANGUAGES.length) { String format = BUILTIN_FORMATS_ALL_LANGUAGES[index]; if (format != null) { return format; } } // In other cases, give priority to using the externally provided format if (!StringUtils.isEmpty(defaultFormat) && !defaultFormat.startsWith(RESERVED)) { return defaultFormat; } // Finally, try using the built-in format String[] builtinFormat = switchBuiltinFormats(locale); if (index >= builtinFormat.length) { return defaultFormat; } return builtinFormat[index]; } public static String[] switchBuiltinFormats(Locale locale) { if (locale != null && Locale.US.getCountry().equals(locale.getCountry())) { return BUILTIN_FORMATS_US; } return BUILTIN_FORMATS_CN; } public static Map<String, Short> switchBuiltinFormatsMap(Locale locale) { if (locale != null && Locale.US.getCountry().equals(locale.getCountry())) { return BUILTIN_FORMATS_MAP_US; } return BUILTIN_FORMATS_MAP_CN; } private static Map<String, Short> buildMap(String[] builtinFormats) { Map<String, Short> map = MapUtils.newHashMapWithExpectedSize(builtinFormats.length); for (int i = 0; i < builtinFormats.length; i++) { map.put(builtinFormats[i], (short)i); } return map; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/constant/EasyExcelConstants.java
easyexcel-core/src/main/java/com/alibaba/excel/constant/EasyExcelConstants.java
package com.alibaba.excel.constant; import java.math.MathContext; import java.math.RoundingMode; /** * Used to store constant * * @author Jiaju Zhuang */ public class EasyExcelConstants { /** * Excel by default with 15 to store Numbers, and the double in Java can use to store number 17, led to the accuracy * will be a problem. So you need to set up 15 to deal with precision */ public static final MathContext EXCEL_MATH_CONTEXT = new MathContext(15, RoundingMode.HALF_UP); }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java
easyexcel-core/src/main/java/com/alibaba/excel/constant/ExcelXmlConstants.java
package com.alibaba.excel.constant; /** * @author jipengfei */ public class ExcelXmlConstants { public static final String DIMENSION_TAG = "dimension"; public static final String ROW_TAG = "row"; public static final String CELL_FORMULA_TAG = "f"; public static final String CELL_VALUE_TAG = "v"; /** * When the data is "inlineStr" his tag is "t" */ public static final String CELL_INLINE_STRING_VALUE_TAG = "t"; public static final String CELL_TAG = "c"; public static final String MERGE_CELL_TAG = "mergeCell"; public static final String HYPERLINK_TAG = "hyperlink"; public static final String X_DIMENSION_TAG = "x:dimension"; public static final String NS2_DIMENSION_TAG = "ns2:dimension"; public static final String X_ROW_TAG = "x:row"; public static final String NS2_ROW_TAG = "ns2:row"; public static final String X_CELL_FORMULA_TAG = "x:f"; public static final String NS2_CELL_FORMULA_TAG = "ns2:f"; public static final String X_CELL_VALUE_TAG = "x:v"; public static final String NS2_CELL_VALUE_TAG = "ns2:v"; /** * When the data is "inlineStr" his tag is "t" */ public static final String X_CELL_INLINE_STRING_VALUE_TAG = "x:t"; public static final String NS2_CELL_INLINE_STRING_VALUE_TAG = "ns2:t"; public static final String X_CELL_TAG = "x:c"; public static final String NS2_CELL_TAG = "ns2:c"; public static final String X_MERGE_CELL_TAG = "x:mergeCell"; public static final String NS2_MERGE_CELL_TAG = "ns2:mergeCell"; public static final String X_HYPERLINK_TAG = "x:hyperlink"; public static final String NS2_HYPERLINK_TAG = "ns2:hyperlink"; /** * s attribute */ public static final String ATTRIBUTE_S = "s"; /** * ref attribute */ public static final String ATTRIBUTE_REF = "ref"; /** * r attribute */ public static final String ATTRIBUTE_R = "r"; /** * t attribute */ public static final String ATTRIBUTE_T = "t"; /** * location attribute */ public static final String ATTRIBUTE_LOCATION = "location"; /** * rId attribute */ public static final String ATTRIBUTE_RID = "r:id"; /** * Cell range split */ public static final String CELL_RANGE_SPLIT = ":"; // The following is a constant read the `SharedStrings.xml` /** * text */ public static final String SHAREDSTRINGS_T_TAG = "t"; public static final String SHAREDSTRINGS_X_T_TAG = "x:t"; public static final String SHAREDSTRINGS_NS2_T_TAG = "ns2:t"; /** * SharedStringItem */ public static final String SHAREDSTRINGS_SI_TAG = "si"; public static final String SHAREDSTRINGS_X_SI_TAG = "x:si"; public static final String SHAREDSTRINGS_NS2_SI_TAG = "ns2:si"; /** * Mac 2016 2017 will have this extra field to ignore */ public static final String SHAREDSTRINGS_RPH_TAG = "rPh"; public static final String SHAREDSTRINGS_X_RPH_TAG = "x:rPh"; public static final String SHAREDSTRINGS_NS2_RPH_TAG = "ns2:rPh"; }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/NullObject.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/NullObject.java
package com.alibaba.excel.metadata; /** * Null object. * * @author Jiaju Zhuang */ public class NullObject { }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/GlobalConfiguration.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/GlobalConfiguration.java
package com.alibaba.excel.metadata; import java.util.Locale; import com.alibaba.excel.enums.CacheLocationEnum; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * Global configuration * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class GlobalConfiguration { /** * Automatic trim includes sheet name and content */ private Boolean autoTrim; /** * true if date uses 1904 windowing, or false if using 1900 date windowing. * * default is false * * @return */ private Boolean use1904windowing; /** * A <code>Locale</code> object represents a specific geographical, political, or cultural region. This parameter is * used when formatting dates and numbers. */ private Locale locale; /** * Whether to use scientific Format. * * default is false */ private Boolean useScientificFormat; /** * The cache used when parsing fields such as head. * * default is THREAD_LOCAL. */ private CacheLocationEnum filedCacheLocation; public GlobalConfiguration() { this.autoTrim = Boolean.TRUE; this.use1904windowing = Boolean.FALSE; this.locale = Locale.getDefault(); this.useScientificFormat = Boolean.FALSE; this.filedCacheLocation = CacheLocationEnum.THREAD_LOCAL; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/AbstractParameterBuilder.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/AbstractParameterBuilder.java
package com.alibaba.excel.metadata; import java.util.List; import java.util.Locale; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CacheLocationEnum; import com.alibaba.excel.util.ListUtils; /** * ExcelBuilder * * @author Jiaju Zhuang */ public abstract class AbstractParameterBuilder<T extends AbstractParameterBuilder, C extends BasicParameter> { /** * You can only choose one of the {@link #head(List)} and {@link #head(Class)} * * @param head * @return */ public T head(List<List<String>> head) { parameter().setHead(head); return self(); } /** * You can only choose one of the {@link #head(List)} and {@link #head(Class)} * * @param clazz * @return */ public T head(Class<?> clazz) { parameter().setClazz(clazz); return self(); } /** * Custom type conversions override the default. * * @param converter * @return */ public T registerConverter(Converter<?> converter) { if (parameter().getCustomConverterList() == null) { parameter().setCustomConverterList(ListUtils.newArrayList()); } parameter().getCustomConverterList().add(converter); return self(); } /** * true if date uses 1904 windowing, or false if using 1900 date windowing. * * default is false * * @param use1904windowing * @return */ public T use1904windowing(Boolean use1904windowing) { parameter().setUse1904windowing(use1904windowing); return self(); } /** * A <code>Locale</code> object represents a specific geographical, political, or cultural region. This parameter is * used when formatting dates and numbers. * * @param locale * @return */ public T locale(Locale locale) { parameter().setLocale(locale); return self(); } /** * The cache used when parsing fields such as head. * * default is THREAD_LOCAL. * * @since 3.3.0 */ public T filedCacheLocation(CacheLocationEnum filedCacheLocation) { parameter().setFiledCacheLocation(filedCacheLocation); return self(); } /** * Automatic trim includes sheet name and content * * @param autoTrim * @return */ public T autoTrim(Boolean autoTrim) { parameter().setAutoTrim(autoTrim); return self(); } @SuppressWarnings("unchecked") protected T self() { return (T)this; } /** * Get parameter * * @return */ protected abstract C parameter(); }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/Head.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/Head.java
package com.alibaba.excel.metadata; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.metadata.property.ColumnWidthProperty; import com.alibaba.excel.metadata.property.FontProperty; import com.alibaba.excel.metadata.property.LoopMergeProperty; import com.alibaba.excel.metadata.property.StyleProperty; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * excel head * * @author Jiaju Zhuang **/ @Getter @Setter @EqualsAndHashCode public class Head { /** * Column index of head */ private Integer columnIndex; /** * It only has values when passed in {@link Sheet#setClazz(Class)} and {@link Table#setClazz(Class)} */ private Field field; /** * It only has values when passed in {@link Sheet#setClazz(Class)} and {@link Table#setClazz(Class)} */ private String fieldName; /** * Head name */ private List<String> headNameList; /** * Whether index is specified */ private Boolean forceIndex; /** * Whether to specify a name */ private Boolean forceName; /** * column with */ private ColumnWidthProperty columnWidthProperty; /** * Loop merge */ private LoopMergeProperty loopMergeProperty; /** * Head style */ private StyleProperty headStyleProperty; /** * Head font */ private FontProperty headFontProperty; public Head(Integer columnIndex, Field field, String fieldName, List<String> headNameList, Boolean forceIndex, Boolean forceName) { this.columnIndex = columnIndex; this.field = field; this.fieldName = fieldName; if (headNameList == null) { this.headNameList = new ArrayList<>(); } else { this.headNameList = headNameList; for (String headName : headNameList) { if (headName == null) { throw new ExcelGenerateException("head name can not be null."); } } } this.forceIndex = forceIndex; this.forceName = forceName; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/CellExtra.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/CellExtra.java
package com.alibaba.excel.metadata; import org.apache.poi.ss.util.CellReference; import com.alibaba.excel.constant.ExcelXmlConstants; import com.alibaba.excel.enums.CellExtraTypeEnum; /** * Cell extra information. * * @author Jiaju Zhuang */ public class CellExtra extends AbstractCell { /** * Cell extra type */ private CellExtraTypeEnum type; /** * Cell extra data */ private String text; /** * First row index, if this object is an interval */ private Integer firstRowIndex; /** * Last row index, if this object is an interval */ private Integer lastRowIndex; /** * First column index, if this object is an interval */ private Integer firstColumnIndex; /** * Last column index, if this object is an interval */ private Integer lastColumnIndex; public CellExtra(CellExtraTypeEnum type, String text, String range) { super(); this.type = type; this.text = text; String[] ranges = range.split(ExcelXmlConstants.CELL_RANGE_SPLIT); CellReference first = new CellReference(ranges[0]); CellReference last = first; this.firstRowIndex = first.getRow(); this.firstColumnIndex = (int)first.getCol(); setRowIndex(this.firstRowIndex); setColumnIndex(this.firstColumnIndex); if (ranges.length > 1) { last = new CellReference(ranges[1]); } this.lastRowIndex = last.getRow(); this.lastColumnIndex = (int)last.getCol(); } public CellExtra(CellExtraTypeEnum type, String text, Integer rowIndex, Integer columnIndex) { this(type, text, rowIndex, rowIndex, columnIndex, columnIndex); } public CellExtra(CellExtraTypeEnum type, String text, Integer firstRowIndex, Integer lastRowIndex, Integer firstColumnIndex, Integer lastColumnIndex) { super(); setRowIndex(firstRowIndex); setColumnIndex(firstColumnIndex); this.type = type; this.text = text; this.firstRowIndex = firstRowIndex; this.firstColumnIndex = firstColumnIndex; this.lastRowIndex = lastRowIndex; this.lastColumnIndex = lastColumnIndex; } public CellExtraTypeEnum getType() { return type; } public void setType(CellExtraTypeEnum type) { this.type = type; } public String getText() { return text; } public void setText(String text) { this.text = text; } public Integer getFirstRowIndex() { return firstRowIndex; } public void setFirstRowIndex(Integer firstRowIndex) { this.firstRowIndex = firstRowIndex; } public Integer getFirstColumnIndex() { return firstColumnIndex; } public void setFirstColumnIndex(Integer firstColumnIndex) { this.firstColumnIndex = firstColumnIndex; } public Integer getLastRowIndex() { return lastRowIndex; } public void setLastRowIndex(Integer lastRowIndex) { this.lastRowIndex = lastRowIndex; } public Integer getLastColumnIndex() { return lastColumnIndex; } public void setLastColumnIndex(Integer lastColumnIndex) { this.lastColumnIndex = lastColumnIndex; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/CellRange.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/CellRange.java
package com.alibaba.excel.metadata; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * @author jipengfei */ @Getter @Setter @EqualsAndHashCode public class CellRange { private int firstRow; private int lastRow; private int firstCol; private int lastCol; public CellRange(int firstRow, int lastRow, int firstCol, int lastCol) { this.firstRow = firstRow; this.lastRow = lastRow; this.firstCol = firstCol; this.lastCol = lastCol; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/AbstractHolder.java
package com.alibaba.excel.metadata; import java.util.List; import java.util.Map; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.ConverterKeyBuild.ConverterKey; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * Write/read holder * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode @NoArgsConstructor public abstract class AbstractHolder implements ConfigurationHolder { /** * Record whether it's new or from cache */ private Boolean newInitialization; /** * You can only choose one of the {@link AbstractHolder#head} and {@link AbstractHolder#clazz} */ private List<List<String>> head; /** * You can only choose one of the {@link AbstractHolder#head} and {@link AbstractHolder#clazz} */ private Class<?> clazz; /** * Some global variables */ private GlobalConfiguration globalConfiguration; /** * <p> * Read key: * <p> * Write key: */ private Map<ConverterKey, Converter<?>> converterMap; public AbstractHolder(BasicParameter basicParameter, AbstractHolder prentAbstractHolder) { this.newInitialization = Boolean.TRUE; if (basicParameter.getHead() == null && basicParameter.getClazz() == null && prentAbstractHolder != null) { this.head = prentAbstractHolder.getHead(); } else { this.head = basicParameter.getHead(); } if (basicParameter.getHead() == null && basicParameter.getClazz() == null && prentAbstractHolder != null) { this.clazz = prentAbstractHolder.getClazz(); } else { this.clazz = basicParameter.getClazz(); } this.globalConfiguration = new GlobalConfiguration(); if (basicParameter.getAutoTrim() == null) { if (prentAbstractHolder != null) { globalConfiguration.setAutoTrim(prentAbstractHolder.getGlobalConfiguration().getAutoTrim()); } } else { globalConfiguration.setAutoTrim(basicParameter.getAutoTrim()); } if (basicParameter.getUse1904windowing() == null) { if (prentAbstractHolder != null) { globalConfiguration.setUse1904windowing( prentAbstractHolder.getGlobalConfiguration().getUse1904windowing()); } } else { globalConfiguration.setUse1904windowing(basicParameter.getUse1904windowing()); } if (basicParameter.getLocale() == null) { if (prentAbstractHolder != null) { globalConfiguration.setLocale(prentAbstractHolder.getGlobalConfiguration().getLocale()); } } else { globalConfiguration.setLocale(basicParameter.getLocale()); } if (basicParameter.getFiledCacheLocation() == null) { if (prentAbstractHolder != null) { globalConfiguration.setFiledCacheLocation( prentAbstractHolder.getGlobalConfiguration().getFiledCacheLocation()); } } else { globalConfiguration.setFiledCacheLocation(basicParameter.getFiledCacheLocation()); } } @Override public Map<ConverterKey, Converter<?>> converterMap() { return getConverterMap(); } @Override public GlobalConfiguration globalConfiguration() { return getGlobalConfiguration(); } @Override public boolean isNew() { return getNewInitialization(); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/FieldWrapper.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/FieldWrapper.java
package com.alibaba.excel.metadata; import java.lang.reflect.Field; import java.util.Map; import java.util.Set; import com.alibaba.excel.annotation.ExcelProperty; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * filed wrapper * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode @AllArgsConstructor @NoArgsConstructor public class FieldWrapper { /** * field */ private Field field; /** * The field name matching cglib */ private String fieldName; /** * The name of the sheet header. * * @see ExcelProperty */ private String[] heads; }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/FieldCache.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/FieldCache.java
package com.alibaba.excel.metadata; import java.lang.reflect.Field; import java.util.Map; import java.util.Set; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * filed cache * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode @AllArgsConstructor public class FieldCache { /** * A field cache that has been sorted by a class. * It will exclude fields that are not needed. */ private Map<Integer, FieldWrapper> sortedFieldMap; /** * Fields using the index attribute */ private Map<Integer, FieldWrapper> indexFieldMap; }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/Font.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/Font.java
package com.alibaba.excel.metadata; /** * * @author jipengfei * @deprecated please use {@link com.alibaba.excel.write.metadata.style.WriteFont} */ @Deprecated public class Font { /** */ private String fontName; /** */ private short fontHeightInPoints; /** */ private boolean bold; public String getFontName() { return fontName; } public void setFontName(String fontName) { this.fontName = fontName; } public short getFontHeightInPoints() { return fontHeightInPoints; } public void setFontHeightInPoints(short fontHeightInPoints) { this.fontHeightInPoints = fontHeightInPoints; } public boolean isBold() { return bold; } public void setBold(boolean bold) { this.bold = bold; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/Cell.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/Cell.java
package com.alibaba.excel.metadata; /** * Cell * * @author Jiaju Zhuang **/ public interface Cell { /** * Row index * * @return */ Integer getRowIndex(); /** * Column index * * @return */ Integer getColumnIndex(); }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/ConfigurationHolder.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/ConfigurationHolder.java
package com.alibaba.excel.metadata; import java.util.Map; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.converters.ConverterKeyBuild.ConverterKey; /** * Get the corresponding holder * * @author Jiaju Zhuang **/ public interface ConfigurationHolder extends Holder { /** * Record whether it's new or from cache * * @return Record whether it's new or from cache */ boolean isNew(); /** * Some global variables * * @return Global configuration */ GlobalConfiguration globalConfiguration(); /** * What converter does the currently operated cell need to execute * * @return Converter */ Map<ConverterKey, Converter<?>> converterMap(); }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/BasicParameter.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/BasicParameter.java
package com.alibaba.excel.metadata; import java.util.List; import java.util.Locale; import com.alibaba.excel.converters.Converter; import com.alibaba.excel.enums.CacheLocationEnum; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * Basic parameter * * @author Jiaju Zhuang **/ @Getter @Setter @EqualsAndHashCode public class BasicParameter { /** * You can only choose one of the {@link BasicParameter#head} and {@link BasicParameter#clazz} */ private List<List<String>> head; /** * You can only choose one of the {@link BasicParameter#head} and {@link BasicParameter#clazz} */ private Class<?> clazz; /** * Custom type conversions override the default */ private List<Converter<?>> customConverterList; /** * Automatic trim includes sheet name and content */ private Boolean autoTrim; /** * true if date uses 1904 windowing, or false if using 1900 date windowing. * * default is false * * @return */ private Boolean use1904windowing; /** * A <code>Locale</code> object represents a specific geographical, political, or cultural region. This parameter is * used when formatting dates and numbers. */ private Locale locale; /** * Whether to use scientific Format. * * default is false */ private Boolean useScientificFormat; /** * The cache used when parsing fields such as head. * * default is THREAD_LOCAL. */ private CacheLocationEnum filedCacheLocation; }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/AbstractCell.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/AbstractCell.java
package com.alibaba.excel.metadata; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * cell * * @author Jiaju Zhuang **/ @Getter @Setter @EqualsAndHashCode public class AbstractCell implements Cell { /** * Row index */ private Integer rowIndex; /** * Column index */ private Integer columnIndex; }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/Holder.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/Holder.java
package com.alibaba.excel.metadata; import com.alibaba.excel.enums.HolderEnum; /** * * Get the corresponding holder * * @author Jiaju Zhuang **/ public interface Holder { /** * What holder is the return * * @return Holder enum. */ HolderEnum holderType(); }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/ColumnWidthProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/ColumnWidthProperty.java
package com.alibaba.excel.metadata.property; import com.alibaba.excel.annotation.write.style.ColumnWidth; /** * Configuration from annotations * * @author Jiaju Zhuang */ public class ColumnWidthProperty { private Integer width; public ColumnWidthProperty(Integer width) { this.width = width; } public static ColumnWidthProperty build(ColumnWidth columnWidth) { if (columnWidth == null || columnWidth.value() < 0) { return null; } return new ColumnWidthProperty(columnWidth.value()); } public Integer getWidth() { return width; } public void setWidth(Integer width) { this.width = width; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/RowHeightProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/RowHeightProperty.java
package com.alibaba.excel.metadata.property; import com.alibaba.excel.annotation.write.style.ContentRowHeight; import com.alibaba.excel.annotation.write.style.HeadRowHeight; /** * Configuration from annotations * * @author Jiaju Zhuang */ public class RowHeightProperty { private Short height; public RowHeightProperty(Short height) { this.height = height; } public static RowHeightProperty build(HeadRowHeight headRowHeight) { if (headRowHeight == null || headRowHeight.value() < 0) { return null; } return new RowHeightProperty(headRowHeight.value()); } public static RowHeightProperty build(ContentRowHeight contentRowHeight) { if (contentRowHeight == null || contentRowHeight.value() < 0) { return null; } return new RowHeightProperty(contentRowHeight.value()); } public Short getHeight() { return height; } public void setHeight(Short height) { this.height = height; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/OnceAbsoluteMergeProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/OnceAbsoluteMergeProperty.java
package com.alibaba.excel.metadata.property; import com.alibaba.excel.annotation.write.style.OnceAbsoluteMerge; /** * Configuration from annotations * * @author Jiaju Zhuang */ public class OnceAbsoluteMergeProperty { /** * First row */ private int firstRowIndex; /** * Last row */ private int lastRowIndex; /** * First column */ private int firstColumnIndex; /** * Last row */ private int lastColumnIndex; public OnceAbsoluteMergeProperty(int firstRowIndex, int lastRowIndex, int firstColumnIndex, int lastColumnIndex) { this.firstRowIndex = firstRowIndex; this.lastRowIndex = lastRowIndex; this.firstColumnIndex = firstColumnIndex; this.lastColumnIndex = lastColumnIndex; } public static OnceAbsoluteMergeProperty build(OnceAbsoluteMerge onceAbsoluteMerge) { if (onceAbsoluteMerge == null) { return null; } return new OnceAbsoluteMergeProperty(onceAbsoluteMerge.firstRowIndex(), onceAbsoluteMerge.lastRowIndex(), onceAbsoluteMerge.firstColumnIndex(), onceAbsoluteMerge.lastColumnIndex()); } public int getFirstRowIndex() { return firstRowIndex; } public void setFirstRowIndex(int firstRowIndex) { this.firstRowIndex = firstRowIndex; } public int getLastRowIndex() { return lastRowIndex; } public void setLastRowIndex(int lastRowIndex) { this.lastRowIndex = lastRowIndex; } public int getFirstColumnIndex() { return firstColumnIndex; } public void setFirstColumnIndex(int firstColumnIndex) { this.firstColumnIndex = firstColumnIndex; } public int getLastColumnIndex() { return lastColumnIndex; } public void setLastColumnIndex(int lastColumnIndex) { this.lastColumnIndex = lastColumnIndex; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/LoopMergeProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/LoopMergeProperty.java
package com.alibaba.excel.metadata.property; import com.alibaba.excel.annotation.write.style.ContentLoopMerge; /** * Configuration from annotations * * @author Jiaju Zhuang */ public class LoopMergeProperty { /** * Each row */ private int eachRow; /** * Extend column */ private int columnExtend; public LoopMergeProperty(int eachRow, int columnExtend) { this.eachRow = eachRow; this.columnExtend = columnExtend; } public static LoopMergeProperty build(ContentLoopMerge contentLoopMerge) { if (contentLoopMerge == null) { return null; } return new LoopMergeProperty(contentLoopMerge.eachRow(), contentLoopMerge.columnExtend()); } public int getEachRow() { return eachRow; } public void setEachRow(int eachRow) { this.eachRow = eachRow; } public int getColumnExtend() { return columnExtend; } public void setColumnExtend(int columnExtend) { this.columnExtend = columnExtend; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/FontProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/FontProperty.java
package com.alibaba.excel.metadata.property; import com.alibaba.excel.annotation.write.style.ContentFontStyle; import com.alibaba.excel.annotation.write.style.HeadFontStyle; import com.alibaba.excel.util.StringUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.poi.common.usermodel.fonts.FontCharset; import org.apache.poi.hssf.usermodel.HSSFPalette; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.IndexedColors; /** * Configuration from annotations * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class FontProperty { /** * The name for the font (i.e. Arial) */ private String fontName; /** * Height in the familiar unit of measure - points */ private Short fontHeightInPoints; /** * Whether to use italics or not */ private Boolean italic; /** * Whether to use a strikeout horizontal line through the text or not */ private Boolean strikeout; /** * The color for the font * * @see Font#COLOR_NORMAL * @see Font#COLOR_RED * @see HSSFPalette#getColor(short) * @see IndexedColors */ private Short color; /** * Set normal, super or subscript. * * @see Font#SS_NONE * @see Font#SS_SUPER * @see Font#SS_SUB */ private Short typeOffset; /** * set type of text underlining to use * * @see Font#U_NONE * @see Font#U_SINGLE * @see Font#U_DOUBLE * @see Font#U_SINGLE_ACCOUNTING * @see Font#U_DOUBLE_ACCOUNTING */ private Byte underline; /** * Set character-set to use. * * @see FontCharset * @see Font#ANSI_CHARSET * @see Font#DEFAULT_CHARSET * @see Font#SYMBOL_CHARSET */ private Integer charset; /** * Bold */ private Boolean bold; public static FontProperty build(HeadFontStyle headFontStyle) { if (headFontStyle == null) { return null; } FontProperty styleProperty = new FontProperty(); if (StringUtils.isNotBlank(headFontStyle.fontName())) { styleProperty.setFontName(headFontStyle.fontName()); } if (headFontStyle.fontHeightInPoints() >= 0) { styleProperty.setFontHeightInPoints(headFontStyle.fontHeightInPoints()); } styleProperty.setItalic(headFontStyle.italic().getBooleanValue()); styleProperty.setStrikeout(headFontStyle.strikeout().getBooleanValue()); if (headFontStyle.color() >= 0) { styleProperty.setColor(headFontStyle.color()); } if (headFontStyle.typeOffset() >= 0) { styleProperty.setTypeOffset(headFontStyle.typeOffset()); } if (headFontStyle.underline() >= 0) { styleProperty.setUnderline(headFontStyle.underline()); } if (headFontStyle.charset() >= 0) { styleProperty.setCharset(headFontStyle.charset()); } styleProperty.setBold(headFontStyle.bold().getBooleanValue()); return styleProperty; } public static FontProperty build(ContentFontStyle contentFontStyle) { if (contentFontStyle == null) { return null; } FontProperty styleProperty = new FontProperty(); if (StringUtils.isNotBlank(contentFontStyle.fontName())) { styleProperty.setFontName(contentFontStyle.fontName()); } if (contentFontStyle.fontHeightInPoints() >= 0) { styleProperty.setFontHeightInPoints(contentFontStyle.fontHeightInPoints()); } styleProperty.setItalic(contentFontStyle.italic().getBooleanValue()); styleProperty.setStrikeout(contentFontStyle.strikeout().getBooleanValue()); if (contentFontStyle.color() >= 0) { styleProperty.setColor(contentFontStyle.color()); } if (contentFontStyle.typeOffset() >= 0) { styleProperty.setTypeOffset(contentFontStyle.typeOffset()); } if (contentFontStyle.underline() >= 0) { styleProperty.setUnderline(contentFontStyle.underline()); } if (contentFontStyle.charset() >= 0) { styleProperty.setCharset(contentFontStyle.charset()); } styleProperty.setBold(contentFontStyle.bold().getBooleanValue()); return styleProperty; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/StyleProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/StyleProperty.java
package com.alibaba.excel.metadata.property; import com.alibaba.excel.annotation.write.style.ContentStyle; import com.alibaba.excel.annotation.write.style.HeadStyle; import com.alibaba.excel.metadata.data.DataFormatData; import com.alibaba.excel.write.metadata.style.WriteFont; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.BuiltinFormats; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.IgnoredErrorType; import org.apache.poi.ss.usermodel.IndexedColors; import org.apache.poi.ss.usermodel.VerticalAlignment; /** * Configuration from annotations * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class StyleProperty { /** * Set the data format (must be a valid format). Built in formats are defined at {@link BuiltinFormats}. */ private DataFormatData dataFormatData; /** * Set the font for this style */ private WriteFont writeFont; /** * Set the cell's using this style to be hidden */ private Boolean hidden; /** * Set the cell's using this style to be locked */ private Boolean locked; /** * Turn on or off "Quote Prefix" or "123 Prefix" for the style, which is used to tell Excel that the thing which * looks like a number or a formula shouldn't be treated as on. Turning this on is somewhat (but not completely, see * {@link IgnoredErrorType}) like prefixing the cell value with a ' in Excel */ private Boolean quotePrefix; /** * Set the type of horizontal alignment for the cell */ private HorizontalAlignment horizontalAlignment; /** * Set whether the text should be wrapped. Setting this flag to <code>true</code> make all content visible within a * cell by displaying it on multiple lines */ private Boolean wrapped; /** * Set the type of vertical alignment for the cell */ private VerticalAlignment verticalAlignment; /** * Set the degree of rotation for the text in the cell. * * Note: HSSF uses values from -90 to 90 degrees, whereas XSSF uses values from 0 to 180 degrees. The * implementations of this method will map between these two value-ranges accordingly, however the corresponding * getter is returning values in the range mandated by the current type of Excel file-format that this CellStyle is * applied to. */ private Short rotation; /** * Set the number of spaces to indent the text in the cell */ private Short indent; /** * Set the type of border to use for the left border of the cell */ private BorderStyle borderLeft; /** * Set the type of border to use for the right border of the cell */ private BorderStyle borderRight; /** * Set the type of border to use for the top border of the cell */ private BorderStyle borderTop; /** * Set the type of border to use for the bottom border of the cell */ private BorderStyle borderBottom; /** * Set the color to use for the left border * * @see IndexedColors */ private Short leftBorderColor; /** * Set the color to use for the right border * * @see IndexedColors */ private Short rightBorderColor; /** * Set the color to use for the top border * * @see IndexedColors */ private Short topBorderColor; /** * Set the color to use for the bottom border * * @see IndexedColors */ private Short bottomBorderColor; /** * Setting to one fills the cell with the foreground color... No idea about other values * * @see FillPatternType#SOLID_FOREGROUND */ private FillPatternType fillPatternType; /** * Set the background fill color. * * @see IndexedColors */ private Short fillBackgroundColor; /** * Set the foreground fill color <i>Note: Ensure Foreground color is set prior to background color.</i> * * @see IndexedColors */ private Short fillForegroundColor; /** * Controls if the Cell should be auto-sized to shrink to fit if the text is too long */ private Boolean shrinkToFit; public static StyleProperty build(HeadStyle headStyle) { if (headStyle == null) { return null; } StyleProperty styleProperty = new StyleProperty(); if (headStyle.dataFormat() >= 0) { DataFormatData dataFormatData = new DataFormatData(); dataFormatData.setIndex(headStyle.dataFormat()); styleProperty.setDataFormatData(dataFormatData); } styleProperty.setHidden(headStyle.hidden().getBooleanValue()); styleProperty.setLocked(headStyle.locked().getBooleanValue()); styleProperty.setQuotePrefix(headStyle.quotePrefix().getBooleanValue()); styleProperty.setHorizontalAlignment(headStyle.horizontalAlignment().getPoiHorizontalAlignment()); styleProperty.setWrapped(headStyle.wrapped().getBooleanValue()); styleProperty.setVerticalAlignment(headStyle.verticalAlignment().getPoiVerticalAlignmentEnum()); if (headStyle.rotation() >= 0) { styleProperty.setRotation(headStyle.rotation()); } if (headStyle.indent() >= 0) { styleProperty.setIndent(headStyle.indent()); } styleProperty.setBorderLeft(headStyle.borderLeft().getPoiBorderStyle()); styleProperty.setBorderRight(headStyle.borderRight().getPoiBorderStyle()); styleProperty.setBorderTop(headStyle.borderTop().getPoiBorderStyle()); styleProperty.setBorderBottom(headStyle.borderBottom().getPoiBorderStyle()); if (headStyle.leftBorderColor() >= 0) { styleProperty.setLeftBorderColor(headStyle.leftBorderColor()); } if (headStyle.rightBorderColor() >= 0) { styleProperty.setRightBorderColor(headStyle.rightBorderColor()); } if (headStyle.topBorderColor() >= 0) { styleProperty.setTopBorderColor(headStyle.topBorderColor()); } if (headStyle.bottomBorderColor() >= 0) { styleProperty.setBottomBorderColor(headStyle.bottomBorderColor()); } styleProperty.setFillPatternType(headStyle.fillPatternType().getPoiFillPatternType()); if (headStyle.fillBackgroundColor() >= 0) { styleProperty.setFillBackgroundColor(headStyle.fillBackgroundColor()); } if (headStyle.fillForegroundColor() >= 0) { styleProperty.setFillForegroundColor(headStyle.fillForegroundColor()); } styleProperty.setShrinkToFit(headStyle.shrinkToFit().getBooleanValue()); return styleProperty; } public static StyleProperty build(ContentStyle contentStyle) { if (contentStyle == null) { return null; } StyleProperty styleProperty = new StyleProperty(); if (contentStyle.dataFormat() >= 0) { DataFormatData dataFormatData = new DataFormatData(); dataFormatData.setIndex(contentStyle.dataFormat()); styleProperty.setDataFormatData(dataFormatData); } styleProperty.setHidden(contentStyle.hidden().getBooleanValue()); styleProperty.setLocked(contentStyle.locked().getBooleanValue()); styleProperty.setQuotePrefix(contentStyle.quotePrefix().getBooleanValue()); styleProperty.setHorizontalAlignment(contentStyle.horizontalAlignment().getPoiHorizontalAlignment()); styleProperty.setWrapped(contentStyle.wrapped().getBooleanValue()); styleProperty.setVerticalAlignment(contentStyle.verticalAlignment().getPoiVerticalAlignmentEnum()); if (contentStyle.rotation() >= 0) { styleProperty.setRotation(contentStyle.rotation()); } if (contentStyle.indent() >= 0) { styleProperty.setIndent(contentStyle.indent()); } styleProperty.setBorderLeft(contentStyle.borderLeft().getPoiBorderStyle()); styleProperty.setBorderRight(contentStyle.borderRight().getPoiBorderStyle()); styleProperty.setBorderTop(contentStyle.borderTop().getPoiBorderStyle()); styleProperty.setBorderBottom(contentStyle.borderBottom().getPoiBorderStyle()); if (contentStyle.leftBorderColor() >= 0) { styleProperty.setLeftBorderColor(contentStyle.leftBorderColor()); } if (contentStyle.rightBorderColor() >= 0) { styleProperty.setRightBorderColor(contentStyle.rightBorderColor()); } if (contentStyle.topBorderColor() >= 0) { styleProperty.setTopBorderColor(contentStyle.topBorderColor()); } if (contentStyle.bottomBorderColor() >= 0) { styleProperty.setBottomBorderColor(contentStyle.bottomBorderColor()); } styleProperty.setFillPatternType(contentStyle.fillPatternType().getPoiFillPatternType()); if (contentStyle.fillBackgroundColor() >= 0) { styleProperty.setFillBackgroundColor(contentStyle.fillBackgroundColor()); } if (contentStyle.fillForegroundColor() >= 0) { styleProperty.setFillForegroundColor(contentStyle.fillForegroundColor()); } styleProperty.setShrinkToFit(contentStyle.shrinkToFit().getBooleanValue()); return styleProperty; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/NumberFormatProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/NumberFormatProperty.java
package com.alibaba.excel.metadata.property; import java.math.RoundingMode; import com.alibaba.excel.annotation.format.NumberFormat; /** * Configuration from annotations * * @author Jiaju Zhuang */ public class NumberFormatProperty { private String format; private RoundingMode roundingMode; public NumberFormatProperty(String format, RoundingMode roundingMode) { this.format = format; this.roundingMode = roundingMode; } public static NumberFormatProperty build(NumberFormat numberFormat) { if (numberFormat == null) { return null; } return new NumberFormatProperty(numberFormat.value(), numberFormat.roundingMode()); } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } public RoundingMode getRoundingMode() { return roundingMode; } public void setRoundingMode(RoundingMode roundingMode) { this.roundingMode = roundingMode; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/ExcelContentProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/ExcelContentProperty.java
package com.alibaba.excel.metadata.property; import java.lang.reflect.Field; import com.alibaba.excel.converters.Converter; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * @author jipengfei */ @Getter @Setter @EqualsAndHashCode public class ExcelContentProperty { public static final ExcelContentProperty EMPTY = new ExcelContentProperty(); /** * Java field */ private Field field; /** * Custom defined converters */ private Converter<?> converter; /** * date time format */ private DateTimeFormatProperty dateTimeFormatProperty; /** * number format */ private NumberFormatProperty numberFormatProperty; /** * Content style */ private StyleProperty contentStyleProperty; /** * Content font */ private FontProperty contentFontProperty; }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/ExcelHeadProperty.java
package com.alibaba.excel.metadata.property; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.TreeMap; import com.alibaba.excel.annotation.ExcelProperty; import com.alibaba.excel.enums.HeadKindEnum; import com.alibaba.excel.metadata.ConfigurationHolder; import com.alibaba.excel.metadata.FieldCache; import com.alibaba.excel.metadata.FieldWrapper; import com.alibaba.excel.metadata.Head; import com.alibaba.excel.metadata.Holder; import com.alibaba.excel.util.ClassUtils; import com.alibaba.excel.util.FieldUtils; import com.alibaba.excel.util.MapUtils; import com.alibaba.excel.util.StringUtils; import com.alibaba.excel.write.metadata.holder.AbstractWriteHolder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.commons.collections4.CollectionUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Define the header attribute of excel * * @author jipengfei */ @Getter @Setter @EqualsAndHashCode public class ExcelHeadProperty { private static final Logger LOGGER = LoggerFactory.getLogger(ExcelHeadProperty.class); /** * Custom class */ private Class<?> headClazz; /** * The types of head */ private HeadKindEnum headKind; /** * The number of rows in the line with the most rows */ private int headRowNumber; /** * Configuration header information */ private Map<Integer, Head> headMap; public ExcelHeadProperty(ConfigurationHolder configurationHolder, Class<?> headClazz, List<List<String>> head) { this.headClazz = headClazz; headMap = new TreeMap<>(); headKind = HeadKindEnum.NONE; headRowNumber = 0; if (head != null && !head.isEmpty()) { int headIndex = 0; for (int i = 0; i < head.size(); i++) { if (configurationHolder instanceof AbstractWriteHolder) { if (((AbstractWriteHolder)configurationHolder).ignore(null, i)) { continue; } } headMap.put(headIndex, new Head(headIndex, null, null, head.get(i), Boolean.FALSE, Boolean.TRUE)); headIndex++; } headKind = HeadKindEnum.STRING; } // convert headClazz to head initColumnProperties(configurationHolder); initHeadRowNumber(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("The initialization sheet/table 'ExcelHeadProperty' is complete , head kind is {}", headKind); } } private void initHeadRowNumber() { headRowNumber = 0; for (Head head : headMap.values()) { List<String> list = head.getHeadNameList(); if (list != null && list.size() > headRowNumber) { headRowNumber = list.size(); } } for (Head head : headMap.values()) { List<String> list = head.getHeadNameList(); if (list != null && !list.isEmpty() && list.size() < headRowNumber) { int lack = headRowNumber - list.size(); int last = list.size() - 1; for (int i = 0; i < lack; i++) { list.add(list.get(last)); } } } } private void initColumnProperties(ConfigurationHolder configurationHolder) { if (headClazz == null) { return; } FieldCache fieldCache = ClassUtils.declaredFields(headClazz, configurationHolder); for (Map.Entry<Integer, FieldWrapper> entry : fieldCache.getSortedFieldMap().entrySet()) { initOneColumnProperty(entry.getKey(), entry.getValue(), fieldCache.getIndexFieldMap().containsKey(entry.getKey())); } headKind = HeadKindEnum.CLASS; } /** * Initialization column property * * @param index * @param field * @param forceIndex * @return Ignore current field */ private void initOneColumnProperty(int index, FieldWrapper field, Boolean forceIndex) { List<String> tmpHeadList = new ArrayList<>(); boolean notForceName = field.getHeads() == null || field.getHeads().length == 0 || (field.getHeads().length == 1 && StringUtils.isEmpty(field.getHeads()[0])); if (headMap.containsKey(index)) { tmpHeadList.addAll(headMap.get(index).getHeadNameList()); } else { if (notForceName) { tmpHeadList.add(field.getFieldName()); } else { Collections.addAll(tmpHeadList, field.getHeads()); } } Head head = new Head(index, field.getField(), field.getFieldName(), tmpHeadList, forceIndex, !notForceName); headMap.put(index, head); } public boolean hasHead() { return headKind != HeadKindEnum.NONE; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/DateTimeFormatProperty.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/property/DateTimeFormatProperty.java
package com.alibaba.excel.metadata.property; import com.alibaba.excel.annotation.format.DateTimeFormat; import com.alibaba.excel.util.BooleanUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * Configuration from annotations * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class DateTimeFormatProperty { private String format; private Boolean use1904windowing; public DateTimeFormatProperty(String format, Boolean use1904windowing) { this.format = format; this.use1904windowing = use1904windowing; } public static DateTimeFormatProperty build(DateTimeFormat dateTimeFormat) { if (dateTimeFormat == null) { return null; } return new DateTimeFormatProperty(dateTimeFormat.value(), BooleanUtils.isTrue(dateTimeFormat.use1904windowing().getBooleanValue())); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/format/ExcelGeneralNumberFormat.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/format/ExcelGeneralNumberFormat.java
package com.alibaba.excel.metadata.format; import java.math.BigDecimal; import java.math.MathContext; import java.math.RoundingMode; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; import java.util.Locale; import org.apache.poi.ss.usermodel.DataFormatter; /** * Written with reference to {@link org.apache.poi.ss.usermodel.ExcelGeneralNumberFormat }. * <p> * Supported Do not use scientific notation. * * @author JiaJu Zhuang **/ public class ExcelGeneralNumberFormat extends Format { private static final long serialVersionUID = 1L; private static final MathContext TO_10_SF = new MathContext(10, RoundingMode.HALF_UP); private final DecimalFormatSymbols decimalSymbols; private final DecimalFormat integerFormat; private final DecimalFormat decimalFormat; private final DecimalFormat scientificFormat; public ExcelGeneralNumberFormat(final Locale locale, final boolean useScientificFormat) { decimalSymbols = DecimalFormatSymbols.getInstance(locale); // Supported Do not use scientific notation. if (useScientificFormat) { scientificFormat = new DecimalFormat("0.#####E0", decimalSymbols); } else { scientificFormat = new DecimalFormat("#", decimalSymbols); } org.apache.poi.ss.usermodel.DataFormatter.setExcelStyleRoundingMode(scientificFormat); integerFormat = new DecimalFormat("#", decimalSymbols); org.apache.poi.ss.usermodel.DataFormatter.setExcelStyleRoundingMode(integerFormat); decimalFormat = new DecimalFormat("#.##########", decimalSymbols); DataFormatter.setExcelStyleRoundingMode(decimalFormat); } @Override public StringBuffer format(Object number, StringBuffer toAppendTo, FieldPosition pos) { final double value; if (number instanceof Number) { value = ((Number) number).doubleValue(); if (Double.isInfinite(value) || Double.isNaN(value)) { return integerFormat.format(number, toAppendTo, pos); } } else { // testBug54786 gets here with a date, so retain previous behaviour return integerFormat.format(number, toAppendTo, pos); } final double abs = Math.abs(value); if (abs >= 1E11 || (abs <= 1E-10 && abs > 0)) { return scientificFormat.format(number, toAppendTo, pos); } else if (Math.floor(value) == value || abs >= 1E10) { // integer, or integer portion uses all 11 allowed digits return integerFormat.format(number, toAppendTo, pos); } // Non-integers of non-scientific magnitude are formatted as "up to 11 // numeric characters, with the decimal point counting as a numeric // character". We know there is a decimal point, so limit to 10 digits. // https://support.microsoft.com/en-us/kb/65903 final double rounded = new BigDecimal(value).round(TO_10_SF).doubleValue(); return decimalFormat.format(rounded, toAppendTo, pos); } @Override public Object parseObject(String source, ParsePosition pos) { throw new UnsupportedOperationException(); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/format/DataFormatter.java
/* * ==================================================================== Licensed to the Apache Software Foundation (ASF) * under one or more contributor license agreements. See the NOTICE file distributed with this work for additional * information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the * License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. * * 2012 - Alfresco Software, Ltd. Alfresco Software has modified source of this file The details of changes as svn diff * can be found in svn at location root/projects/3rd-party/src * ==================================================================== */ package com.alibaba.excel.metadata.format; import java.math.BigDecimal; import java.math.RoundingMode; import java.text.DateFormatSymbols; import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; import java.text.FieldPosition; import java.text.Format; import java.text.ParsePosition; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.alibaba.excel.util.DateUtils; import org.apache.poi.ss.format.CellFormat; import org.apache.poi.ss.format.CellFormatResult; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.ExcelStyleDateFormatter; import org.apache.poi.ss.usermodel.FractionFormat; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Written with reference to {@link org.apache.poi.ss.usermodel.DataFormatter}.Made some optimizations for date * conversion. * <p> * This is a non-thread-safe class. * * @author Jiaju Zhuang */ public class DataFormatter { /** * For logging any problems we find */ private static final Logger LOGGER = LoggerFactory.getLogger(DataFormatter.class); private static final String defaultFractionWholePartFormat = "#"; private static final String defaultFractionFractionPartFormat = "#/##"; /** * Pattern to find a number format: "0" or "#" */ private static final Pattern numPattern = Pattern.compile("[0#]+"); /** * Pattern to find days of week as text "ddd...." */ private static final Pattern daysAsText = Pattern.compile("([d]{3,})", Pattern.CASE_INSENSITIVE); /** * Pattern to find "AM/PM" marker */ private static final Pattern amPmPattern = Pattern.compile("(([AP])[M/P]*)|(([上下])[午/下]*)", Pattern.CASE_INSENSITIVE); /** * Pattern to find formats with condition ranges e.g. [>=100] */ private static final Pattern rangeConditionalPattern = Pattern.compile(".*\\[\\s*(>|>=|<|<=|=)\\s*[0-9]*\\.*[0-9].*"); /** * A regex to find locale patterns like [$$-1009] and [$?-452]. Note that we don't currently process these into * locales */ private static final Pattern localePatternGroup = Pattern.compile("(\\[\\$[^-\\]]*-[0-9A-Z]+])"); /** * A regex to match the colour formattings rules. Allowed colours are: Black, Blue, Cyan, Green, Magenta, Red, * White, Yellow, "Color n" (1<=n<=56) */ private static final Pattern colorPattern = Pattern.compile( "(\\[BLACK])|(\\[BLUE])|(\\[CYAN])|(\\[GREEN])|" + "(\\[MAGENTA])|(\\[RED])|(\\[WHITE])|(\\[YELLOW])|" + "(\\[COLOR\\s*\\d])|(\\[COLOR\\s*[0-5]\\d])|(\\[DBNum(1|2|3)])|(\\[\\$-\\d{0,3}])", Pattern.CASE_INSENSITIVE); /** * A regex to identify a fraction pattern. This requires that replaceAll("\\?", "#") has already been called */ private static final Pattern fractionPattern = Pattern.compile("(?:([#\\d]+)\\s+)?(#+)\\s*/\\s*([#\\d]+)"); /** * A regex to strip junk out of fraction formats */ private static final Pattern fractionStripper = Pattern.compile("(\"[^\"]*\")|([^ ?#\\d/]+)"); /** * A regex to detect if an alternate grouping character is used in a numeric format */ private static final Pattern alternateGrouping = Pattern.compile("([#0]([^.#0])[#0]{3})"); private static final Pattern E_NOTATION_PATTERN = Pattern.compile("E(\\d)"); /** * Cells formatted with a date or time format and which contain invalid date or time values show 255 pound signs * ("#"). */ private static final String invalidDateTimeString; static { StringBuilder buf = new StringBuilder(); for (int i = 0; i < 255; i++) {buf.append('#');} invalidDateTimeString = buf.toString(); } /** * The decimal symbols of the locale used for formatting values. */ private DecimalFormatSymbols decimalSymbols; /** * The date symbols of the locale used for formatting values. */ private DateFormatSymbols dateSymbols; /** * A default format to use when a number pattern cannot be parsed. */ private Format defaultNumFormat; /** * A map to cache formats. Map<String,Format> formats */ private final Map<String, Format> formats = new HashMap<String, Format>(); /** * stores the locale valid it the last formatting call */ private Locale locale; /** * true if date uses 1904 windowing, or false if using 1900 date windowing. * * default is false * * @return */ private Boolean use1904windowing; /** * Whether to use scientific Format. * * default is false */ private Boolean useScientificFormat; /** * Creates a formatter using the given locale. */ public DataFormatter(Boolean use1904windowing, Locale locale, Boolean useScientificFormat) { if (use1904windowing == null) { this.use1904windowing = Boolean.FALSE; } else { this.use1904windowing = use1904windowing; } if (locale == null) { this.locale = Locale.getDefault(); } else { this.locale = locale; } if (use1904windowing == null) { this.useScientificFormat = Boolean.FALSE; } else { this.useScientificFormat = useScientificFormat; } this.dateSymbols = DateFormatSymbols.getInstance(this.locale); this.decimalSymbols = DecimalFormatSymbols.getInstance(this.locale); } private Format getFormat(Double data, Short dataFormat, String dataFormatString) { // Might be better to separate out the n p and z formats, falling back to p when n and z are not set. // That however would require other code to be re factored. // String[] formatBits = formatStrIn.split(";"); // int i = cellValue > 0.0 ? 0 : cellValue < 0.0 ? 1 : 2; // String formatStr = (i < formatBits.length) ? formatBits[i] : formatBits[0]; String formatStr = dataFormatString; // Excel supports 2+ part conditional data formats, eg positive/negative/zero, // or (>1000),(>0),(0),(negative). As Java doesn't handle these kinds // of different formats for different ranges, just +ve/-ve, we need to // handle these ourselves in a special way. // For now, if we detect 2+ parts, we call out to CellFormat to handle it // TODO Going forward, we should really merge the logic between the two classes if (formatStr.contains(";") && (formatStr.indexOf(';') != formatStr.lastIndexOf(';') || rangeConditionalPattern.matcher(formatStr).matches() )) { try { // Ask CellFormat to get a formatter for it CellFormat cfmt = CellFormat.getInstance(locale, formatStr); // CellFormat requires callers to identify date vs not, so do so Object cellValueO = data; if (DateUtils.isADateFormat(dataFormat, formatStr) && // don't try to handle Date value 0, let a 3 or 4-part format take care of it data.doubleValue() != 0.0) { cellValueO = DateUtils.getJavaDate(data, use1904windowing); } // Wrap and return (non-cachable - CellFormat does that) return new CellFormatResultWrapper(cfmt.apply(cellValueO)); } catch (Exception e) { LOGGER.warn("Formatting failed for format {}, falling back", formatStr, e); } } // See if we already have it cached Format format = formats.get(formatStr); if (format != null) { return format; } // Is it one of the special built in types, General or @? if ("General".equalsIgnoreCase(formatStr) || "@".equals(formatStr)) { format = getDefaultFormat(); addFormat(formatStr, format); return format; } // Build a formatter, and cache it format = createFormat(dataFormat, formatStr); addFormat(formatStr, format); return format; } private Format createFormat(Short dataFormat, String dataFormatString) { String formatStr = dataFormatString; Format format = checkSpecialConverter(formatStr); if (format != null) { return format; } // Remove colour formatting if present Matcher colourM = colorPattern.matcher(formatStr); while (colourM.find()) { String colour = colourM.group(); // Paranoid replacement... int at = formatStr.indexOf(colour); if (at == -1) {break;} String nFormatStr = formatStr.substring(0, at) + formatStr.substring(at + colour.length()); if (nFormatStr.equals(formatStr)) {break;} // Try again in case there's multiple formatStr = nFormatStr; colourM = colorPattern.matcher(formatStr); } // Strip off the locale information, we use an instance-wide locale for everything Matcher m = localePatternGroup.matcher(formatStr); while (m.find()) { String match = m.group(); String symbol = match.substring(match.indexOf('$') + 1, match.indexOf('-')); if (symbol.indexOf('$') > -1) { symbol = symbol.substring(0, symbol.indexOf('$')) + '\\' + symbol.substring(symbol.indexOf('$')); } formatStr = m.replaceAll(symbol); m = localePatternGroup.matcher(formatStr); } // Check for special cases if (formatStr == null || formatStr.trim().length() == 0) { return getDefaultFormat(); } if ("General".equalsIgnoreCase(formatStr) || "@".equals(formatStr)) { return getDefaultFormat(); } if (DateUtils.isADateFormat(dataFormat, formatStr)) { return createDateFormat(formatStr); } // Excel supports fractions in format strings, which Java doesn't if (formatStr.contains("#/") || formatStr.contains("?/")) { String[] chunks = formatStr.split(";"); for (String chunk1 : chunks) { String chunk = chunk1.replaceAll("\\?", "#"); Matcher matcher = fractionStripper.matcher(chunk); chunk = matcher.replaceAll(" "); chunk = chunk.replaceAll(" +", " "); Matcher fractionMatcher = fractionPattern.matcher(chunk); // take the first match if (fractionMatcher.find()) { String wholePart = (fractionMatcher.group(1) == null) ? "" : defaultFractionWholePartFormat; return new FractionFormat(wholePart, fractionMatcher.group(3)); } } // Strip custom text in quotes and escaped characters for now as it can cause performance problems in // fractions. // String strippedFormatStr = formatStr.replaceAll("\\\\ ", " ").replaceAll("\\\\.", // "").replaceAll("\"[^\"]*\"", " ").replaceAll("\\?", "#"); return new FractionFormat(defaultFractionWholePartFormat, defaultFractionFractionPartFormat); } if (numPattern.matcher(formatStr).find()) { return createNumberFormat(formatStr); } return getDefaultFormat(); } private Format checkSpecialConverter(String dataFormatString) { if ("00000\\-0000".equals(dataFormatString) || "00000-0000".equals(dataFormatString)) { return new ZipPlusFourFormat(); } if ("[<=9999999]###\\-####;\\(###\\)\\ ###\\-####".equals(dataFormatString) || "[<=9999999]###-####;(###) ###-####".equals(dataFormatString) || "###\\-####;\\(###\\)\\ ###\\-####".equals(dataFormatString) || "###-####;(###) ###-####".equals(dataFormatString)) { return new PhoneFormat(); } if ("000\\-00\\-0000".equals(dataFormatString) || "000-00-0000".equals(dataFormatString)) { return new SSNFormat(); } return null; } private Format createDateFormat(String pFormatStr) { String formatStr = pFormatStr; formatStr = formatStr.replaceAll("\\\\-", "-"); formatStr = formatStr.replaceAll("\\\\,", ","); formatStr = formatStr.replaceAll("\\\\\\.", "."); // . is a special regexp char formatStr = formatStr.replaceAll("\\\\ ", " "); formatStr = formatStr.replaceAll("\\\\/", "/"); // weird: m\\/d\\/yyyy formatStr = formatStr.replaceAll(";@", ""); formatStr = formatStr.replaceAll("\"/\"", "/"); // "/" is escaped for no reason in: mm"/"dd"/"yyyy formatStr = formatStr.replace("\"\"", "'"); // replace Excel quoting with Java style quoting formatStr = formatStr.replaceAll("\\\\T", "'T'"); // Quote the T is iso8601 style dates formatStr = formatStr.replace("\"", ""); boolean hasAmPm = false; Matcher amPmMatcher = amPmPattern.matcher(formatStr); while (amPmMatcher.find()) { formatStr = amPmMatcher.replaceAll("@"); hasAmPm = true; amPmMatcher = amPmPattern.matcher(formatStr); } formatStr = formatStr.replaceAll("@", "a"); Matcher dateMatcher = daysAsText.matcher(formatStr); if (dateMatcher.find()) { String match = dateMatcher.group(0).toUpperCase(Locale.ROOT).replaceAll("D", "E"); formatStr = dateMatcher.replaceAll(match); } // Convert excel date format to SimpleDateFormat. // Excel uses lower and upper case 'm' for both minutes and months. // From Excel help: /* The "m" or "mm" code must appear immediately after the "h" or"hh" code or immediately before the "ss" code; otherwise, Microsoft Excel displays the month instead of minutes." */ StringBuilder sb = new StringBuilder(); char[] chars = formatStr.toCharArray(); boolean mIsMonth = true; List<Integer> ms = new ArrayList<Integer>(); boolean isElapsed = false; for (int j = 0; j < chars.length; j++) { char c = chars[j]; if (c == '\'') { sb.append(c); j++; // skip until the next quote while (j < chars.length) { c = chars[j]; sb.append(c); if (c == '\'') { break; } j++; } } else if (c == '[' && !isElapsed) { isElapsed = true; mIsMonth = false; sb.append(c); } else if (c == ']' && isElapsed) { isElapsed = false; sb.append(c); } else if (isElapsed) { if (c == 'h' || c == 'H') { sb.append('H'); } else if (c == 'm' || c == 'M') { sb.append('m'); } else if (c == 's' || c == 'S') { sb.append('s'); } else { sb.append(c); } } else if (c == 'h' || c == 'H') { mIsMonth = false; if (hasAmPm) { sb.append('h'); } else { sb.append('H'); } } else if (c == 'm' || c == 'M') { if (mIsMonth) { sb.append('M'); ms.add(Integer.valueOf(sb.length() - 1)); } else { sb.append('m'); } } else if (c == 's' || c == 'S') { sb.append('s'); // if 'M' precedes 's' it should be minutes ('m') for (int index : ms) { if (sb.charAt(index) == 'M') { sb.replace(index, index + 1, "m"); } } mIsMonth = true; ms.clear(); } else if (Character.isLetter(c)) { mIsMonth = true; ms.clear(); if (c == 'y' || c == 'Y') { sb.append('y'); } else if (c == 'd' || c == 'D') { sb.append('d'); } else { sb.append(c); } } else { if (Character.isWhitespace(c)) { ms.clear(); } sb.append(c); } } formatStr = sb.toString(); try { return new ExcelStyleDateFormatter(formatStr, dateSymbols); } catch (IllegalArgumentException iae) { LOGGER.debug("Formatting failed for format {}, falling back", formatStr, iae); // the pattern could not be parsed correctly, // so fall back to the default number format return getDefaultFormat(); } } private String cleanFormatForNumber(String formatStr) { StringBuilder sb = new StringBuilder(formatStr); // If they requested spacers, with "_", // remove those as we don't do spacing // If they requested full-column-width // padding, with "*", remove those too for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); if (c == '_' || c == '*') { if (i > 0 && sb.charAt((i - 1)) == '\\') { // It's escaped, don't worry continue; } if (i < sb.length() - 1) { // Remove the character we're supposed // to match the space of / pad to the // column width with sb.deleteCharAt(i + 1); } // Remove the _ too sb.deleteCharAt(i); i--; } } // Now, handle the other aspects like // quoting and scientific notation for (int i = 0; i < sb.length(); i++) { char c = sb.charAt(i); // remove quotes and back slashes if (c == '\\' || c == '"') { sb.deleteCharAt(i); i--; // for scientific/engineering notation } else if (c == '+' && i > 0 && sb.charAt(i - 1) == 'E') { sb.deleteCharAt(i); i--; } } return sb.toString(); } private static class InternalDecimalFormatWithScale extends Format { private static final Pattern endsWithCommas = Pattern.compile("(,+)$"); private BigDecimal divider; private static final BigDecimal ONE_THOUSAND = new BigDecimal(1000); private final DecimalFormat df; private static String trimTrailingCommas(String s) { return s.replaceAll(",+$", ""); } public InternalDecimalFormatWithScale(String pattern, DecimalFormatSymbols symbols) { df = new DecimalFormat(trimTrailingCommas(pattern), symbols); setExcelStyleRoundingMode(df); Matcher endsWithCommasMatcher = endsWithCommas.matcher(pattern); if (endsWithCommasMatcher.find()) { String commas = (endsWithCommasMatcher.group(1)); BigDecimal temp = BigDecimal.ONE; for (int i = 0; i < commas.length(); ++i) { temp = temp.multiply(ONE_THOUSAND); } divider = temp; } else { divider = null; } } private Object scaleInput(Object obj) { if (divider != null) { if (obj instanceof BigDecimal) { obj = ((BigDecimal)obj).divide(divider, RoundingMode.HALF_UP); } else if (obj instanceof Double) { obj = (Double)obj / divider.doubleValue(); } else { throw new UnsupportedOperationException(); } } return obj; } @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { obj = scaleInput(obj); return df.format(obj, toAppendTo, pos); } @Override public Object parseObject(String source, ParsePosition pos) { throw new UnsupportedOperationException(); } } private Format createNumberFormat(String formatStr) { String format = cleanFormatForNumber(formatStr); DecimalFormatSymbols symbols = decimalSymbols; // Do we need to change the grouping character? // eg for a format like #'##0 which wants 12'345 not 12,345 Matcher agm = alternateGrouping.matcher(format); if (agm.find()) { char grouping = agm.group(2).charAt(0); // Only replace the grouping character if it is not the default // grouping character for the US locale (',') in order to enable // correct grouping for non-US locales. if (grouping != ',') { symbols = DecimalFormatSymbols.getInstance(locale); symbols.setGroupingSeparator(grouping); String oldPart = agm.group(1); String newPart = oldPart.replace(grouping, ','); format = format.replace(oldPart, newPart); } } try { return new InternalDecimalFormatWithScale(format, symbols); } catch (IllegalArgumentException iae) { LOGGER.error("Formatting failed for format {}, falling back", formatStr, iae); // the pattern could not be parsed correctly, // so fall back to the default number format return getDefaultFormat(); } } private Format getDefaultFormat() { // for numeric cells try user supplied default if (defaultNumFormat != null) { return defaultNumFormat; // otherwise use general format } defaultNumFormat = new ExcelGeneralNumberFormat(locale, useScientificFormat); return defaultNumFormat; } /** * Performs Excel-style date formatting, using the supplied Date and format */ private String performDateFormatting(Date d, Format dateFormat) { Format df = dateFormat != null ? dateFormat : getDefaultFormat(); return df.format(d); } /** * Returns the formatted value of an Excel date as a <tt>String</tt> based on the cell's <code>DataFormat</code>. * i.e. "Thursday, January 02, 2003" , "01/02/2003" , "02-Jan" , etc. * <p> * If any conditional format rules apply, the highest priority with a number format is used. If no rules contain a * number format, or no rules apply, the cell's style format is used. If the style does not have a format, the * default date format is applied. * * @param data to format * @param dataFormat * @param dataFormatString * @return Formatted value */ private String getFormattedDateString(Double data, Short dataFormat, String dataFormatString) { Format dateFormat = getFormat(data, dataFormat, dataFormatString); if (dateFormat instanceof ExcelStyleDateFormatter) { // Hint about the raw excel value ((ExcelStyleDateFormatter)dateFormat).setDateToBeFormatted(data); } return performDateFormatting(DateUtils.getJavaDate(data, use1904windowing), dateFormat); } /** * Returns the formatted value of an Excel number as a <tt>String</tt> based on the cell's <code>DataFormat</code>. * Supported formats include currency, percents, decimals, phone number, SSN, etc.: "61.54%", "$100.00", "(800) * 555-1234". * <p> * Format comes from either the highest priority conditional format rule with a specified format, or from the cell * style. * * @param data to format * @param dataFormat * @param dataFormatString * @return a formatted number string */ private String getFormattedNumberString(BigDecimal data, Short dataFormat, String dataFormatString) { Format numberFormat = getFormat(data.doubleValue(), dataFormat, dataFormatString); return E_NOTATION_PATTERN.matcher(numberFormat.format(data)).replaceFirst("E+$1"); } /** * Format data. * * @param data * @param dataFormat * @param dataFormatString * @return */ public String format(BigDecimal data, Short dataFormat, String dataFormatString) { if (DateUtils.isADateFormat(dataFormat, dataFormatString)) { return getFormattedDateString(data.doubleValue(), dataFormat, dataFormatString); } return getFormattedNumberString(data, dataFormat, dataFormatString); } /** * <p> * Sets a default number format to be used when the Excel format cannot be parsed successfully. <b>Note:</b> This is * a fall back for when an error occurs while parsing an Excel number format pattern. This will not affect cells * with the <em>General</em> format. * </p> * <p> * The value that will be passed to the Format's format method (specified by <code>java.text.Format#format</code>) * will be a double value from a numeric cell. Therefore the code in the format method should expect a * <code>Number</code> value. * </p> * * @param format A Format instance to be used as a default * @see Format#format */ public void setDefaultNumberFormat(Format format) { for (Map.Entry<String, Format> entry : formats.entrySet()) { if (entry.getValue() == defaultNumFormat) { entry.setValue(format); } } defaultNumFormat = format; } /** * Adds a new format to the available formats. * <p> * The value that will be passed to the Format's format method (specified by <code>java.text.Format#format</code>) * will be a double value from a numeric cell. Therefore the code in the format method should expect a * <code>Number</code> value. * </p> * * @param excelFormatStr The data format string * @param format A Format instance */ public void addFormat(String excelFormatStr, Format format) { formats.put(excelFormatStr, format); } // Some custom formats /** * @return a <tt>DecimalFormat</tt> with parseIntegerOnly set <code>true</code> */ private static DecimalFormat createIntegerOnlyFormat(String fmt) { DecimalFormatSymbols dsf = DecimalFormatSymbols.getInstance(Locale.ROOT); DecimalFormat result = new DecimalFormat(fmt, dsf); result.setParseIntegerOnly(true); return result; } /** * Enables excel style rounding mode (round half up) on the Decimal Format given. */ public static void setExcelStyleRoundingMode(DecimalFormat format) { setExcelStyleRoundingMode(format, RoundingMode.HALF_UP); } /** * Enables custom rounding mode on the given Decimal Format. * * @param format DecimalFormat * @param roundingMode RoundingMode */ public static void setExcelStyleRoundingMode(DecimalFormat format, RoundingMode roundingMode) { format.setRoundingMode(roundingMode); } /** * Format class for Excel's SSN format. This class mimics Excel's built-in SSN formatting. * * @author James May */ @SuppressWarnings("serial") private static final class SSNFormat extends Format { private static final DecimalFormat df = createIntegerOnlyFormat("000000000"); private SSNFormat() { // enforce singleton } /** * Format a number as an SSN */ public static String format(Number num) { String result = df.format(num); return result.substring(0, 3) + '-' + result.substring(3, 5) + '-' + result.substring(5, 9); } @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(format((Number)obj)); } @Override public Object parseObject(String source, ParsePosition pos) { return df.parseObject(source, pos); } } /** * Format class for Excel Zip + 4 format. This class mimics Excel's built-in formatting for Zip + 4. * * @author James May */ @SuppressWarnings("serial") private static final class ZipPlusFourFormat extends Format { private static final DecimalFormat df = createIntegerOnlyFormat("000000000"); private ZipPlusFourFormat() { // enforce singleton } /** * Format a number as Zip + 4 */ public static String format(Number num) { String result = df.format(num); return result.substring(0, 5) + '-' + result.substring(5, 9); } @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(format((Number)obj)); } @Override public Object parseObject(String source, ParsePosition pos) { return df.parseObject(source, pos); } } /** * Format class for Excel phone number format. This class mimics Excel's built-in phone number formatting. * * @author James May */ @SuppressWarnings("serial") private static final class PhoneFormat extends Format { private static final DecimalFormat df = createIntegerOnlyFormat("##########"); private PhoneFormat() { // enforce singleton } /** * Format a number as a phone number */ public static String format(Number num) { String result = df.format(num); StringBuilder sb = new StringBuilder(); String seg1, seg2, seg3; int len = result.length(); if (len <= 4) { return result; } seg3 = result.substring(len - 4, len); seg2 = result.substring(Math.max(0, len - 7), len - 4); seg1 = result.substring(Math.max(0, len - 10), Math.max(0, len - 7)); if (seg1.trim().length() > 0) { sb.append('(').append(seg1).append(") "); } if (seg2.trim().length() > 0) { sb.append(seg2).append('-'); } sb.append(seg3); return sb.toString(); } @Override public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos) { return toAppendTo.append(format((Number)obj)); } @Override public Object parseObject(String source, ParsePosition pos) { return df.parseObject(source, pos); } } /** * Workaround until we merge {@link org.apache.poi.ss.usermodel.DataFormatter} with {@link CellFormat}. Constant, * non-cachable wrapper around a * {@link CellFormatResult} */
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
true
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/FormulaData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/FormulaData.java
package com.alibaba.excel.metadata.data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * formula * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class FormulaData { /** * formula */ private String formulaValue; @Override public FormulaData clone() { FormulaData formulaData = new FormulaData(); formulaData.setFormulaValue(getFormulaValue()); return formulaData; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/HyperlinkData.java
package com.alibaba.excel.metadata.data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * hyperlink * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class HyperlinkData extends CoordinateData { /** * Depending on the hyperlink type it can be URL, e-mail, path to a file, etc */ private String address; /** * hyperlink type */ private HyperlinkType hyperlinkType; @Getter public enum HyperlinkType { /** * Not a hyperlink */ NONE(org.apache.poi.common.usermodel.HyperlinkType.NONE), /** * Link to an existing file or web page */ URL(org.apache.poi.common.usermodel.HyperlinkType.URL), /** * Link to a place in this document */ DOCUMENT(org.apache.poi.common.usermodel.HyperlinkType.DOCUMENT), /** * Link to an E-mail address */ EMAIL(org.apache.poi.common.usermodel.HyperlinkType.EMAIL), /** * Link to a file */ FILE(org.apache.poi.common.usermodel.HyperlinkType.FILE); org.apache.poi.common.usermodel.HyperlinkType value; HyperlinkType(org.apache.poi.common.usermodel.HyperlinkType value) { this.value = value; } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/WriteCellData.java
package com.alibaba.excel.metadata.data; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Date; import java.util.List; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.util.ListUtils; import com.alibaba.excel.write.metadata.style.WriteCellStyle; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.apache.poi.ss.usermodel.CellStyle; /** * write cell data * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode @NoArgsConstructor public class WriteCellData<T> extends CellData<T> { /** * Support only when writing.{@link CellDataTypeEnum#DATE} */ private LocalDateTime dateValue; /** * rich text.{@link CellDataTypeEnum#RICH_TEXT_STRING} */ private RichTextStringData richTextStringDataValue; /** * image */ private List<ImageData> imageDataList; /** * comment */ private CommentData commentData; /** * hyper link */ private HyperlinkData hyperlinkData; /** * style */ private WriteCellStyle writeCellStyle; /** * If originCellStyle is empty, one will be created. * If both writeCellStyle and originCellStyle exist, copy from writeCellStyle to originCellStyle. */ private CellStyle originCellStyle; public WriteCellData(String stringValue) { this(CellDataTypeEnum.STRING, stringValue); } public WriteCellData(CellDataTypeEnum type) { super(); setType(type); } public WriteCellData(CellDataTypeEnum type, String stringValue) { super(); if (type != CellDataTypeEnum.STRING && type != CellDataTypeEnum.ERROR) { throw new IllegalArgumentException("Only support CellDataTypeEnum.STRING and CellDataTypeEnum.ERROR"); } if (stringValue == null) { throw new IllegalArgumentException("StringValue can not be null"); } setType(type); setStringValue(stringValue); } public WriteCellData(BigDecimal numberValue) { super(); if (numberValue == null) { throw new IllegalArgumentException("DoubleValue can not be null"); } setType(CellDataTypeEnum.NUMBER); setNumberValue(numberValue); } public WriteCellData(Boolean booleanValue) { super(); if (booleanValue == null) { throw new IllegalArgumentException("BooleanValue can not be null"); } setType(CellDataTypeEnum.BOOLEAN); setBooleanValue(booleanValue); } public WriteCellData(Date dateValue) { super(); if (dateValue == null) { throw new IllegalArgumentException("DateValue can not be null"); } setType(CellDataTypeEnum.DATE); this.dateValue = LocalDateTime.ofInstant(dateValue.toInstant(), ZoneId.systemDefault()); } public WriteCellData(LocalDateTime dateValue) { super(); if (dateValue == null) { throw new IllegalArgumentException("DateValue can not be null"); } setType(CellDataTypeEnum.DATE); this.dateValue = dateValue; } public WriteCellData(byte[] image) { super(); if (image == null) { throw new IllegalArgumentException("Image can not be null"); } setType(CellDataTypeEnum.EMPTY); this.imageDataList = ListUtils.newArrayList(); ImageData imageData = new ImageData(); imageData.setImage(image); imageDataList.add(imageData); } /** * Return a style, if is empty, create a new * * @return not null. */ public WriteCellStyle getOrCreateStyle() { if (this.writeCellStyle == null) { this.writeCellStyle = new WriteCellStyle(); } return this.writeCellStyle; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/RichTextStringData.java
package com.alibaba.excel.metadata.data; import java.util.List; import com.alibaba.excel.util.ListUtils; import com.alibaba.excel.write.metadata.style.WriteFont; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * rich text string * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode @NoArgsConstructor public class RichTextStringData { private String textString; private WriteFont writeFont; private List<IntervalFont> intervalFontList; public RichTextStringData(String textString) { this.textString = textString; } @Getter @Setter @EqualsAndHashCode @AllArgsConstructor public static class IntervalFont { private Integer startIndex; private Integer endIndex; private WriteFont writeFont; } /** * Applies a font to the specified characters of a string. * * @param startIndex The start index to apply the font to (inclusive) * @param endIndex The end index to apply to font to (exclusive) * @param writeFont The font to use. */ public void applyFont(int startIndex, int endIndex, WriteFont writeFont) { if (intervalFontList == null) { intervalFontList = ListUtils.newArrayList(); } intervalFontList.add(new IntervalFont(startIndex, endIndex, writeFont)); } /** * Sets the font of the entire string. * * @param writeFont The font to use. */ public void applyFont(WriteFont writeFont) { this.writeFont = writeFont; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/ReadCellData.java
package com.alibaba.excel.metadata.data; import java.math.BigDecimal; import java.time.LocalDateTime; import com.alibaba.excel.constant.EasyExcelConstants; import com.alibaba.excel.enums.CellDataTypeEnum; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; /** * read cell data * <p> * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode @NoArgsConstructor public class ReadCellData<T> extends CellData<T> { /** * originalNumberValue vs numberValue * <ol> * <li> * NUMBER: * originalNumberValue: Original data and the accuracy of his is 17, but in fact the excel only 15 precision to * process the data * numberValue: After correction of the data and the accuracy of his is 15 * for example, originalNumberValue = `2087.0249999999996` , numberValue = `2087.03` * </li> * <li> * DATE: * originalNumberValue: Storage is a data type double, accurate to milliseconds * dateValue: Based on double converted to a date format, he will revised date difference, accurate to seconds * for example, originalNumberValue = `44729.99998836806` ,time is:`2022-06-17 23:59:58.995`, * But in excel is displayed:` 2022-06-17 23:59:59`, dateValue = `2022-06-17 23:59:59` * </li> * </ol> * {@link CellDataTypeEnum#NUMBER} {@link CellDataTypeEnum#DATE} */ private BigDecimal originalNumberValue; /** * data format. */ private DataFormatData dataFormatData; public ReadCellData(CellDataTypeEnum type) { super(); if (type == null) { throw new IllegalArgumentException("Type can not be null"); } setType(type); } public ReadCellData(T data) { super(); setData(data); } public ReadCellData(String stringValue) { this(CellDataTypeEnum.STRING, stringValue); } public ReadCellData(CellDataTypeEnum type, String stringValue) { super(); if (type != CellDataTypeEnum.STRING && type != CellDataTypeEnum.ERROR) { throw new IllegalArgumentException("Only support CellDataTypeEnum.STRING and CellDataTypeEnum.ERROR"); } if (stringValue == null) { throw new IllegalArgumentException("StringValue can not be null"); } setType(type); setStringValue(stringValue); } public ReadCellData(BigDecimal numberValue) { super(); if (numberValue == null) { throw new IllegalArgumentException("DoubleValue can not be null"); } setType(CellDataTypeEnum.NUMBER); setNumberValue(numberValue); } public ReadCellData(Boolean booleanValue) { super(); if (booleanValue == null) { throw new IllegalArgumentException("BooleanValue can not be null"); } setType(CellDataTypeEnum.BOOLEAN); setBooleanValue(booleanValue); } public static ReadCellData<?> newEmptyInstance() { return newEmptyInstance(null, null); } public static ReadCellData<?> newEmptyInstance(Integer rowIndex, Integer columnIndex) { ReadCellData<?> cellData = new ReadCellData<>(CellDataTypeEnum.EMPTY); cellData.setRowIndex(rowIndex); cellData.setColumnIndex(columnIndex); return cellData; } public static ReadCellData<?> newInstance(Boolean booleanValue) { return newInstance(booleanValue, null, null); } public static ReadCellData<?> newInstance(Boolean booleanValue, Integer rowIndex, Integer columnIndex) { ReadCellData<?> cellData = new ReadCellData<>(booleanValue); cellData.setRowIndex(rowIndex); cellData.setColumnIndex(columnIndex); return cellData; } public static ReadCellData<?> newInstance(String stringValue, Integer rowIndex, Integer columnIndex) { ReadCellData<?> cellData = new ReadCellData<>(stringValue); cellData.setRowIndex(rowIndex); cellData.setColumnIndex(columnIndex); return cellData; } public static ReadCellData<?> newInstance(BigDecimal numberValue, Integer rowIndex, Integer columnIndex) { ReadCellData<?> cellData = new ReadCellData<>(numberValue); cellData.setRowIndex(rowIndex); cellData.setColumnIndex(columnIndex); return cellData; } public static ReadCellData<?> newInstanceOriginal(BigDecimal numberValue, Integer rowIndex, Integer columnIndex) { ReadCellData<?> cellData = new ReadCellData<>(numberValue); cellData.setRowIndex(rowIndex); cellData.setColumnIndex(columnIndex); cellData.setOriginalNumberValue(numberValue); cellData.setNumberValue(numberValue.round(EasyExcelConstants.EXCEL_MATH_CONTEXT)); return cellData; } @Override public ReadCellData<Object> clone() { ReadCellData<Object> readCellData = new ReadCellData<>(); readCellData.setType(getType()); readCellData.setNumberValue(getNumberValue()); readCellData.setOriginalNumberValue(getOriginalNumberValue()); readCellData.setStringValue(getStringValue()); readCellData.setBooleanValue(getBooleanValue()); readCellData.setData(getData()); if (getDataFormatData() != null) { readCellData.setDataFormatData(getDataFormatData().clone()); } if (getFormulaData() != null) { readCellData.setFormulaData(getFormulaData().clone()); } return readCellData; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/ImageData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/ImageData.java
package com.alibaba.excel.metadata.data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * image * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class ImageData extends ClientAnchorData { /** * image */ private byte[] image; /** * image type */ private ImageType imageType; @Getter public enum ImageType { /** * Extended windows meta file */ PICTURE_TYPE_EMF(2), /** * Windows Meta File */ PICTURE_TYPE_WMF(3), /** * Mac PICT format */ PICTURE_TYPE_PICT(4), /** * JPEG format */ PICTURE_TYPE_JPEG(5), /** * PNG format */ PICTURE_TYPE_PNG(6), /** * Device independent bitmap */ PICTURE_TYPE_DIB(7), ; int value; ImageType(int value) { this.value = value; } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/CoordinateData.java
package com.alibaba.excel.metadata.data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * coordinate. * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class CoordinateData { /** * first row index.Priority is higher than {@link #relativeFirstRowIndex}. */ private Integer firstRowIndex; /** * first column index.Priority is higher than {@link #relativeFirstColumnIndex}. */ private Integer firstColumnIndex; /** * last row index.Priority is higher than {@link #relativeLastRowIndex}. */ private Integer lastRowIndex; /** * last column index.Priority is higher than {@link #relativeLastColumnIndex}. */ private Integer lastColumnIndex; /** * relative first row index */ private Integer relativeFirstRowIndex; /** * relative first column index */ private Integer relativeFirstColumnIndex; /** * relative last row index */ private Integer relativeLastRowIndex; /** *relative last column index */ private Integer relativeLastColumnIndex; }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/DataFormatData.java
package com.alibaba.excel.metadata.data; import com.alibaba.excel.util.StringUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * data format * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class DataFormatData { /** * index */ private Short index; /** * format */ private String format; /** * The source is not empty merge the data to the target. * * @param source source * @param target target */ public static void merge(DataFormatData source, DataFormatData target) { if (source == null || target == null) { return; } if (source.getIndex() != null) { target.setIndex(source.getIndex()); } if (StringUtils.isNotBlank(source.getFormat())) { target.setFormat(source.getFormat()); } } @Override public DataFormatData clone() { DataFormatData dataFormatData = new DataFormatData(); dataFormatData.setIndex(getIndex()); dataFormatData.setFormat(getFormat()); return dataFormatData; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/CellData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/CellData.java
package com.alibaba.excel.metadata.data; import java.math.BigDecimal; import java.time.LocalDateTime; import com.alibaba.excel.enums.CellDataTypeEnum; import com.alibaba.excel.metadata.AbstractCell; import com.alibaba.excel.util.StringUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * Excel internal cell data. * * <p> * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class CellData<T> extends AbstractCell { /** * cell type */ private CellDataTypeEnum type; /** * {@link CellDataTypeEnum#NUMBER} */ private BigDecimal numberValue; /** * {@link CellDataTypeEnum#STRING} and{@link CellDataTypeEnum#ERROR} */ private String stringValue; /** * {@link CellDataTypeEnum#BOOLEAN} */ private Boolean booleanValue; /** * The resulting converted data. */ private T data; /** * formula */ private FormulaData formulaData; /** * Ensure that the object does not appear null */ public void checkEmpty() { if (type == null) { type = CellDataTypeEnum.EMPTY; } switch (type) { case STRING: case DIRECT_STRING: case ERROR: if (StringUtils.isEmpty(stringValue)) { type = CellDataTypeEnum.EMPTY; } return; case NUMBER: if (numberValue == null) { type = CellDataTypeEnum.EMPTY; } return; case BOOLEAN: if (booleanValue == null) { type = CellDataTypeEnum.EMPTY; } return; default: } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/CommentData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/CommentData.java
package com.alibaba.excel.metadata.data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; /** * comment * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class CommentData extends ClientAnchorData { /** * Name of the original comment author */ private String author; /** * rich text string */ private RichTextStringData richTextStringData; }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/data/ClientAnchorData.java
package com.alibaba.excel.metadata.data; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.poi.ss.usermodel.ClientAnchor; import org.apache.poi.util.Internal; /** * A client anchor is attached to an excel worksheet. It anchors against * absolute coordinates, a top-left cell and fixed height and width, or * a top-left and bottom-right cell, depending on the {@link ClientAnchorData.AnchorType}: * <ol> * <li> {@link ClientAnchor.AnchorType#DONT_MOVE_AND_RESIZE} == absolute top-left coordinates and width/height, no * cell references * <li> {@link ClientAnchor.AnchorType#MOVE_DONT_RESIZE} == fixed top-left cell reference, absolute width/height * <li> {@link ClientAnchor.AnchorType#MOVE_AND_RESIZE} == fixed top-left and bottom-right cell references, dynamic * width/height * </ol> * Note this class only reports the current values for possibly calculated positions and sizes. * If the sheet row/column sizes or positions shift, this needs updating via external calculations. * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class ClientAnchorData extends CoordinateData { /** * top */ private Integer top; /** * right */ private Integer right; /** * bottom */ private Integer bottom; /** * left */ private Integer left; /** * anchor type */ private AnchorType anchorType; @Getter public enum AnchorType { /** * Move and Resize With Anchor Cells (0) * <p> * Specifies that the current drawing shall move and * resize to maintain its row and column anchors (i.e. the * object is anchored to the actual from and to row and column) * </p> */ MOVE_AND_RESIZE(ClientAnchor.AnchorType.MOVE_AND_RESIZE), /** * Don't Move but do Resize With Anchor Cells (1) * <p> * Specifies that the current drawing shall not move with its * row and column, but should be resized. This option is not normally * used, but is included for completeness. * </p> * Note: Excel has no setting for this combination, nor does the ECMA standard. */ DONT_MOVE_DO_RESIZE(ClientAnchor.AnchorType.DONT_MOVE_DO_RESIZE), /** * Move With Cells but Do Not Resize (2) * <p> * Specifies that the current drawing shall move with its * row and column (i.e. the object is anchored to the * actual from row and column), but that the size shall remain absolute. * </p> * <p> * If additional rows/columns are added between the from and to locations of the drawing, * the drawing shall move its to anchors as needed to maintain this same absolute size. * </p> */ MOVE_DONT_RESIZE(ClientAnchor.AnchorType.MOVE_DONT_RESIZE), /** * Do Not Move or Resize With Underlying Rows/Columns (3) * <p> * Specifies that the current start and end positions shall * be maintained with respect to the distances from the * absolute start point of the worksheet. * </p> * <p> * If additional rows/columns are added before the * drawing, the drawing shall move its anchors as needed * to maintain this same absolute position. * </p> */ DONT_MOVE_AND_RESIZE(ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE); ClientAnchor.AnchorType value; AnchorType(ClientAnchor.AnchorType value) { this.value = value; } /** * return the AnchorType corresponding to the code * * @param value the anchor type code * @return the anchor type enum */ @Internal public static ClientAnchorData.AnchorType byId(int value) { return values()[value]; } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvRichTextString.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvRichTextString.java
package com.alibaba.excel.metadata.csv; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.RichTextString; /** * rich text string * * @author Jiaju Zhuang */ public class CsvRichTextString implements RichTextString { /** * string */ private final String string; public CsvRichTextString(String string) { this.string = string; } @Override public void applyFont(int startIndex, int endIndex, short fontIndex) { } @Override public void applyFont(int startIndex, int endIndex, Font font) { } @Override public void applyFont(Font font) { } @Override public void clearFormatting() { } @Override public String getString() { return string; } @Override public int length() { if (string == null) { return 0; } return string.length(); } @Override public int numFormattingRuns() { return 0; } @Override public int getIndexOfFormattingRun(int index) { return 0; } @Override public void applyFont(short fontIndex) { } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvRow.java
package com.alibaba.excel.metadata.csv; import java.util.Iterator; import java.util.List; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.compress.utils.Lists; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; /** * csv row * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class CsvRow implements Row { /** * cell list */ private final List<CsvCell> cellList; /** * workbook */ private final CsvWorkbook csvWorkbook; /** * sheet */ private final CsvSheet csvSheet; /** * row index */ private Integer rowIndex; /** * style */ private CellStyle cellStyle; public CsvRow(CsvWorkbook csvWorkbook, CsvSheet csvSheet, Integer rowIndex) { cellList = Lists.newArrayList(); this.csvWorkbook = csvWorkbook; this.csvSheet = csvSheet; this.rowIndex = rowIndex; } @Override public Cell createCell(int column) { CsvCell cell = new CsvCell(csvWorkbook, csvSheet, this, column, null); cellList.add(cell); return cell; } @Override public Cell createCell(int column, CellType type) { CsvCell cell = new CsvCell(csvWorkbook, csvSheet, this, column, type); cellList.add(cell); return cell; } @Override public void removeCell(Cell cell) { cellList.remove(cell); } @Override public void setRowNum(int rowNum) { this.rowIndex = rowNum; } @Override public int getRowNum() { return rowIndex; } @Override public Cell getCell(int cellnum) { if (cellnum >= cellList.size()) { return null; } return cellList.get(cellnum - 1); } @Override public Cell getCell(int cellnum, MissingCellPolicy policy) { return getCell(cellnum); } @Override public short getFirstCellNum() { if (CollectionUtils.isEmpty(cellList)) { return -1; } return 0; } @Override public short getLastCellNum() { if (CollectionUtils.isEmpty(cellList)) { return -1; } return (short)cellList.size(); } @Override public int getPhysicalNumberOfCells() { return getRowNum(); } @Override public void setHeight(short height) { } @Override public void setZeroHeight(boolean zHeight) { } @Override public boolean getZeroHeight() { return false; } @Override public void setHeightInPoints(float height) { } @Override public short getHeight() { return 0; } @Override public float getHeightInPoints() { return 0; } @Override public boolean isFormatted() { return false; } @Override public CellStyle getRowStyle() { return cellStyle; } @Override public void setRowStyle(CellStyle style) { this.cellStyle = style; } @Override public Iterator<Cell> cellIterator() { return (Iterator<Cell>)(Iterator<? extends Cell>)cellList.iterator(); } @Override public Sheet getSheet() { return csvSheet; } @Override public int getOutlineLevel() { return 0; } @Override public void shiftCellsRight(int firstShiftColumnIndex, int lastShiftColumnIndex, int step) { } @Override public void shiftCellsLeft(int firstShiftColumnIndex, int lastShiftColumnIndex, int step) { } @Override public Iterator<Cell> iterator() { return cellIterator(); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvCell.java
package com.alibaba.excel.metadata.csv; import java.math.BigDecimal; import java.time.LocalDateTime; import java.time.ZoneId; import java.util.Calendar; import java.util.Date; import com.alibaba.excel.enums.NumericCellTypeEnum; import com.alibaba.excel.metadata.data.FormulaData; import lombok.AccessLevel; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.usermodel.CellBase; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CellType; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.ss.usermodel.RichTextString; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.util.CellRangeAddress; /** * csv cell * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class CsvCell extends CellBase { /** * column index */ @Getter(value = AccessLevel.NONE) @Setter(value = AccessLevel.NONE) private Integer columnIndex; /** * cell type */ @Getter(value = AccessLevel.NONE) @Setter(value = AccessLevel.NONE) private CellType cellType; /** * numeric cell type */ private NumericCellTypeEnum numericCellType; /** * workbook */ private final CsvWorkbook csvWorkbook; /** * sheet */ private final CsvSheet csvSheet; /** * row */ private final CsvRow csvRow; /** * {@link CellType#NUMERIC} */ private BigDecimal numberValue; /** * {@link CellType#STRING} and {@link CellType#ERROR} {@link CellType#FORMULA} */ private String stringValue; /** * {@link CellType#BOOLEAN} */ private Boolean booleanValue; /** * {@link CellType#NUMERIC} */ private LocalDateTime dateValue; /** * formula */ private FormulaData formulaData; /** * rich text string */ private RichTextString richTextString; /** * style */ private CellStyle cellStyle; public CsvCell(CsvWorkbook csvWorkbook, CsvSheet csvSheet, CsvRow csvRow, Integer columnIndex, CellType cellType) { this.csvWorkbook = csvWorkbook; this.csvSheet = csvSheet; this.csvRow = csvRow; this.columnIndex = columnIndex; this.cellType = cellType; if (this.cellType == null) { this.cellType = CellType._NONE; } } @Override protected void setCellTypeImpl(CellType cellType) { this.cellType = cellType; } @Override protected void setCellFormulaImpl(String formula) { FormulaData formulaData = new FormulaData(); formulaData.setFormulaValue(formula); this.formulaData = formulaData; this.cellType = CellType.FORMULA; } @Override protected void removeFormulaImpl() { this.formulaData = null; } @Override protected void setCellValueImpl(double value) { numberValue = BigDecimal.valueOf(value); this.cellType = CellType.NUMERIC; } @Override protected void setCellValueImpl(Date value) { if (value == null) { return; } this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); this.cellType = CellType.NUMERIC; this.numericCellType = NumericCellTypeEnum.DATE; } @Override protected void setCellValueImpl(LocalDateTime value) { this.dateValue = value; this.cellType = CellType.NUMERIC; this.numericCellType = NumericCellTypeEnum.DATE; } @Override protected void setCellValueImpl(Calendar value) { if (value == null) { return; } this.dateValue = LocalDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()); this.cellType = CellType.NUMERIC; } @Override protected void setCellValueImpl(String value) { this.stringValue = value; this.cellType = CellType.STRING; } @Override protected void setCellValueImpl(RichTextString value) { richTextString = value; this.cellType = CellType.STRING; } @Override public void setCellValue(String value) { if (value == null) { setBlank(); return; } setCellValueImpl(value); } @Override public void setCellValue(RichTextString value) { if (value == null || value.getString() == null) { setBlank(); return; } setCellValueImpl(value); } @Override protected SpreadsheetVersion getSpreadsheetVersion() { return null; } @Override public int getColumnIndex() { return columnIndex; } @Override public int getRowIndex() { return csvRow.getRowNum(); } @Override public Sheet getSheet() { return csvRow.getSheet(); } @Override public Row getRow() { return csvRow; } @Override public CellType getCellType() { return cellType; } @Override public CellType getCachedFormulaResultType() { return getCellType(); } @Override public String getCellFormula() { if (formulaData == null) { return null; } return formulaData.getFormulaValue(); } @Override public double getNumericCellValue() { if (numberValue == null) { return 0; } return numberValue.doubleValue(); } @Override public Date getDateCellValue() { if (dateValue == null) { return null; } return Date.from(dateValue.atZone(ZoneId.systemDefault()).toInstant()); } @Override public LocalDateTime getLocalDateTimeCellValue() { return dateValue; } @Override public RichTextString getRichStringCellValue() { return richTextString; } @Override public String getStringCellValue() { return stringValue; } @Override public void setCellValue(boolean value) { this.booleanValue = value; this.cellType = CellType.BOOLEAN; } @Override public void setCellErrorValue(byte value) { this.numberValue = BigDecimal.valueOf(value); this.cellType = CellType.ERROR; } @Override public boolean getBooleanCellValue() { if (booleanValue == null) { return false; } return booleanValue; } @Override public byte getErrorCellValue() { if (numberValue == null) { return 0; } return numberValue.byteValue(); } @Override public void setCellStyle(CellStyle style) { this.cellStyle = style; } @Override public CellStyle getCellStyle() { return cellStyle; } @Override public void setAsActiveCell() { } @Override public void setCellComment(Comment comment) { } @Override public Comment getCellComment() { return null; } @Override public void removeCellComment() { } @Override public Hyperlink getHyperlink() { return null; } @Override public void setHyperlink(Hyperlink link) { } @Override public void removeHyperlink() { } @Override public CellRangeAddress getArrayFormulaRange() { return null; } @Override public boolean isPartOfArrayFormulaGroup() { return false; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvCellStyle.java
package com.alibaba.excel.metadata.csv; import com.alibaba.excel.metadata.data.DataFormatData; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.poi.ss.usermodel.BorderStyle; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Color; import org.apache.poi.ss.usermodel.FillPatternType; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.HorizontalAlignment; import org.apache.poi.ss.usermodel.VerticalAlignment; /** * csv cell style * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class CsvCellStyle implements CellStyle { /** * data format */ private DataFormatData dataFormatData; /** * index */ private Short index; public CsvCellStyle(Short index) { this.index = index; } @Override public short getIndex() { return index; } @Override public void setDataFormat(short fmt) { initDataFormatData(); dataFormatData.setIndex(fmt); } private void initDataFormatData() { if (dataFormatData == null) { dataFormatData = new DataFormatData(); } } @Override public short getDataFormat() { if (dataFormatData == null) { return 0; } return dataFormatData.getIndex(); } @Override public String getDataFormatString() { if (dataFormatData == null) { return null; } return dataFormatData.getFormat(); } @Override public void setFont(Font font) { } @Override public int getFontIndex() { return 0; } @Override public int getFontIndexAsInt() { return 0; } @Override public void setHidden(boolean hidden) { } @Override public boolean getHidden() { return false; } @Override public void setLocked(boolean locked) { } @Override public boolean getLocked() { return false; } @Override public void setQuotePrefixed(boolean quotePrefix) { } @Override public boolean getQuotePrefixed() { return false; } @Override public void setAlignment(HorizontalAlignment align) { } @Override public HorizontalAlignment getAlignment() { return null; } @Override public void setWrapText(boolean wrapped) { } @Override public boolean getWrapText() { return false; } @Override public void setVerticalAlignment(VerticalAlignment align) { } @Override public VerticalAlignment getVerticalAlignment() { return null; } @Override public void setRotation(short rotation) { } @Override public short getRotation() { return 0; } @Override public void setIndention(short indent) { } @Override public short getIndention() { return 0; } @Override public void setBorderLeft(BorderStyle border) { } @Override public BorderStyle getBorderLeft() { return null; } @Override public void setBorderRight(BorderStyle border) { } @Override public BorderStyle getBorderRight() { return null; } @Override public void setBorderTop(BorderStyle border) { } @Override public BorderStyle getBorderTop() { return null; } @Override public void setBorderBottom(BorderStyle border) { } @Override public BorderStyle getBorderBottom() { return null; } @Override public void setLeftBorderColor(short color) { } @Override public short getLeftBorderColor() { return 0; } @Override public void setRightBorderColor(short color) { } @Override public short getRightBorderColor() { return 0; } @Override public void setTopBorderColor(short color) { } @Override public short getTopBorderColor() { return 0; } @Override public void setBottomBorderColor(short color) { } @Override public short getBottomBorderColor() { return 0; } @Override public void setFillPattern(FillPatternType fp) { } @Override public FillPatternType getFillPattern() { return null; } @Override public void setFillBackgroundColor(short bg) { } @Override public void setFillBackgroundColor(Color color) { } @Override public short getFillBackgroundColor() { return 0; } @Override public Color getFillBackgroundColorColor() { return null; } @Override public void setFillForegroundColor(short bg) { } @Override public void setFillForegroundColor(Color color) { } @Override public short getFillForegroundColor() { return 0; } @Override public Color getFillForegroundColorColor() { return null; } @Override public void cloneStyleFrom(CellStyle source) { } @Override public void setShrinkToFit(boolean shrinkToFit) { } @Override public boolean getShrinkToFit() { return false; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvSheet.java
package com.alibaba.excel.metadata.csv; import java.io.Closeable; import java.io.IOException; import java.math.BigDecimal; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.enums.ByteOrderMarkEnum; import com.alibaba.excel.enums.NumericCellTypeEnum; import com.alibaba.excel.exception.ExcelGenerateException; import com.alibaba.excel.util.DateUtils; import com.alibaba.excel.util.ListUtils; import com.alibaba.excel.util.MapUtils; import com.alibaba.excel.util.NumberDataFormatterUtils; import com.alibaba.excel.util.StringUtils; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.io.ByteOrderMark; import org.apache.poi.ss.usermodel.AutoFilter; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.CellRange; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.Comment; import org.apache.poi.ss.usermodel.DataValidation; import org.apache.poi.ss.usermodel.DataValidationHelper; import org.apache.poi.ss.usermodel.DateUtil; import org.apache.poi.ss.usermodel.Drawing; import org.apache.poi.ss.usermodel.Footer; import org.apache.poi.ss.usermodel.Header; import org.apache.poi.ss.usermodel.Hyperlink; import org.apache.poi.ss.usermodel.PageMargin; import org.apache.poi.ss.usermodel.PaneType; import org.apache.poi.ss.usermodel.PrintSetup; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.SheetConditionalFormatting; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.ss.util.CellAddress; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.ss.util.PaneInformation; /** * csv sheet * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class CsvSheet implements Sheet, Closeable { /** * workbook */ private CsvWorkbook csvWorkbook; /** * output */ private Appendable out; /** * row cache */ private Integer rowCacheCount; /** * format */ public CSVFormat csvFormat; /** * last row index */ private Integer lastRowIndex; /** * row cache */ private List<CsvRow> rowCache; /** * csv printer */ private CSVPrinter csvPrinter; public CsvSheet(CsvWorkbook csvWorkbook, Appendable out) { this.csvWorkbook = csvWorkbook; this.out = out; this.rowCacheCount = 100; this.csvFormat = CSVFormat.DEFAULT; this.lastRowIndex = -1; } @Override public Row createRow(int rownum) { // Initialize the data when the row is first created initSheet(); lastRowIndex++; assert rownum == lastRowIndex : "csv create row must be in order."; printData(); CsvRow csvRow = new CsvRow(csvWorkbook, this, rownum); rowCache.add(csvRow); return csvRow; } private void initSheet() { if (csvPrinter != null) { return; } rowCache = ListUtils.newArrayListWithExpectedSize(rowCacheCount); try { if (csvWorkbook.getWithBom()) { ByteOrderMarkEnum byteOrderMark = ByteOrderMarkEnum.valueOfByCharsetName( csvWorkbook.getCharset().name()); if (byteOrderMark != null) { out.append(byteOrderMark.getStringPrefix()); } } csvPrinter = csvFormat.print(out); } catch (IOException e) { throw new ExcelGenerateException(e); } } @Override public void removeRow(Row row) { throw new UnsupportedOperationException("csv cannot move row."); } @Override public Row getRow(int rownum) { int actualRowIndex = rownum - (lastRowIndex - rowCache.size()) - 1; if (actualRowIndex < 0 || actualRowIndex > rowCache.size() - 1) { throw new UnsupportedOperationException("The current data does not exist or has been flushed to disk\n."); } return rowCache.get(actualRowIndex); } @Override public int getPhysicalNumberOfRows() { return lastRowIndex - rowCache.size(); } @Override public int getFirstRowNum() { if (lastRowIndex < 0) { return -1; } return 0; } @Override public int getLastRowNum() { return lastRowIndex; } @Override public void setColumnHidden(int columnIndex, boolean hidden) { } @Override public boolean isColumnHidden(int columnIndex) { return false; } @Override public void setRightToLeft(boolean value) { } @Override public boolean isRightToLeft() { return false; } @Override public void setColumnWidth(int columnIndex, int width) { } @Override public int getColumnWidth(int columnIndex) { return 0; } @Override public float getColumnWidthInPixels(int columnIndex) { return 0; } @Override public void setDefaultColumnWidth(int width) { } @Override public int getDefaultColumnWidth() { return 0; } @Override public short getDefaultRowHeight() { return 0; } @Override public float getDefaultRowHeightInPoints() { return 0; } @Override public void setDefaultRowHeight(short height) { } @Override public void setDefaultRowHeightInPoints(float height) { } @Override public CellStyle getColumnStyle(int column) { return null; } @Override public int addMergedRegion(CellRangeAddress region) { return 0; } @Override public int addMergedRegionUnsafe(CellRangeAddress region) { return 0; } @Override public void validateMergedRegions() { } @Override public void setVerticallyCenter(boolean value) { } @Override public void setHorizontallyCenter(boolean value) { } @Override public boolean getHorizontallyCenter() { return false; } @Override public boolean getVerticallyCenter() { return false; } @Override public void removeMergedRegion(int index) { } @Override public void removeMergedRegions(Collection<Integer> indices) { } @Override public int getNumMergedRegions() { return 0; } @Override public CellRangeAddress getMergedRegion(int index) { return null; } @Override public List<CellRangeAddress> getMergedRegions() { return null; } @Override public Iterator<Row> rowIterator() { return (Iterator<Row>)(Iterator<? extends Row>)rowCache.iterator(); } @Override public void setForceFormulaRecalculation(boolean value) { } @Override public boolean getForceFormulaRecalculation() { return false; } @Override public void setAutobreaks(boolean value) { } @Override public void setDisplayGuts(boolean value) { } @Override public void setDisplayZeros(boolean value) { } @Override public boolean isDisplayZeros() { return false; } @Override public void setFitToPage(boolean value) { } @Override public void setRowSumsBelow(boolean value) { } @Override public void setRowSumsRight(boolean value) { } @Override public boolean getAutobreaks() { return false; } @Override public boolean getDisplayGuts() { return false; } @Override public boolean getFitToPage() { return false; } @Override public boolean getRowSumsBelow() { return false; } @Override public boolean getRowSumsRight() { return false; } @Override public boolean isPrintGridlines() { return false; } @Override public void setPrintGridlines(boolean show) { } @Override public boolean isPrintRowAndColumnHeadings() { return false; } @Override public void setPrintRowAndColumnHeadings(boolean show) { } @Override public PrintSetup getPrintSetup() { return null; } @Override public Header getHeader() { return null; } @Override public Footer getFooter() { return null; } @Override public void setSelected(boolean value) { } @Override public double getMargin(short margin) { return 0; } @Override public double getMargin(PageMargin pageMargin) { return 0; } @Override public void setMargin(short margin, double size) { } @Override public void setMargin(PageMargin pageMargin, double v) { } @Override public boolean getProtect() { return false; } @Override public void protectSheet(String password) { } @Override public boolean getScenarioProtect() { return false; } @Override public void setZoom(int scale) { } @Override public short getTopRow() { return 0; } @Override public short getLeftCol() { return 0; } @Override public void showInPane(int topRow, int leftCol) { } @Override public void shiftRows(int startRow, int endRow, int n) { } @Override public void shiftRows(int startRow, int endRow, int n, boolean copyRowHeight, boolean resetOriginalRowHeight) { } @Override public void shiftColumns(int startColumn, int endColumn, int n) { } @Override public void createFreezePane(int colSplit, int rowSplit, int leftmostColumn, int topRow) { } @Override public void createFreezePane(int colSplit, int rowSplit) { } @Override public void createSplitPane(int xSplitPos, int ySplitPos, int leftmostColumn, int topRow, int activePane) { } @Override public void createSplitPane(int i, int i1, int i2, int i3, PaneType paneType) { } @Override public PaneInformation getPaneInformation() { return null; } @Override public void setDisplayGridlines(boolean show) { } @Override public boolean isDisplayGridlines() { return false; } @Override public void setDisplayFormulas(boolean show) { } @Override public boolean isDisplayFormulas() { return false; } @Override public void setDisplayRowColHeadings(boolean show) { } @Override public boolean isDisplayRowColHeadings() { return false; } @Override public void setRowBreak(int row) { } @Override public boolean isRowBroken(int row) { return false; } @Override public void removeRowBreak(int row) { } @Override public int[] getRowBreaks() { return new int[0]; } @Override public int[] getColumnBreaks() { return new int[0]; } @Override public void setColumnBreak(int column) { } @Override public boolean isColumnBroken(int column) { return false; } @Override public void removeColumnBreak(int column) { } @Override public void setColumnGroupCollapsed(int columnNumber, boolean collapsed) { } @Override public void groupColumn(int fromColumn, int toColumn) { } @Override public void ungroupColumn(int fromColumn, int toColumn) { } @Override public void groupRow(int fromRow, int toRow) { } @Override public void ungroupRow(int fromRow, int toRow) { } @Override public void setRowGroupCollapsed(int row, boolean collapse) { } @Override public void setDefaultColumnStyle(int column, CellStyle style) { } @Override public void autoSizeColumn(int column) { } @Override public void autoSizeColumn(int column, boolean useMergedCells) { } @Override public Comment getCellComment(CellAddress ref) { return null; } @Override public Map<CellAddress, ? extends Comment> getCellComments() { return null; } @Override public Drawing<?> getDrawingPatriarch() { return null; } @Override public Drawing<?> createDrawingPatriarch() { return null; } @Override public Workbook getWorkbook() { return csvWorkbook; } @Override public String getSheetName() { return null; } @Override public boolean isSelected() { return false; } @Override public CellRange<? extends Cell> setArrayFormula( String formula, CellRangeAddress range) { return null; } @Override public CellRange<? extends Cell> removeArrayFormula(Cell cell) { return null; } @Override public DataValidationHelper getDataValidationHelper() { return null; } @Override public List<? extends DataValidation> getDataValidations() { return null; } @Override public void addValidationData(DataValidation dataValidation) { } @Override public AutoFilter setAutoFilter(CellRangeAddress range) { return null; } @Override public SheetConditionalFormatting getSheetConditionalFormatting() { return null; } @Override public CellRangeAddress getRepeatingRows() { return null; } @Override public CellRangeAddress getRepeatingColumns() { return null; } @Override public void setRepeatingRows(CellRangeAddress rowRangeRef) { } @Override public void setRepeatingColumns(CellRangeAddress columnRangeRef) { } @Override public int getColumnOutlineLevel(int columnIndex) { return 0; } @Override public Hyperlink getHyperlink(int row, int column) { return null; } @Override public Hyperlink getHyperlink(CellAddress addr) { return null; } @Override public List<? extends Hyperlink> getHyperlinkList() { return null; } @Override public CellAddress getActiveCell() { return null; } @Override public void setActiveCell(CellAddress address) { } @Override public Iterator<Row> iterator() { return rowIterator(); } @Override public void close() throws IOException { // Avoid empty sheets initSheet(); flushData(); csvPrinter.flush(); csvPrinter.close(); } public void printData() { if (rowCache.size() >= rowCacheCount) { flushData(); } } public void flushData() { try { for (CsvRow row : rowCache) { Iterator<Cell> cellIterator = row.cellIterator(); int columnIndex = 0; while (cellIterator.hasNext()) { CsvCell csvCell = (CsvCell)cellIterator.next(); while (csvCell.getColumnIndex() > columnIndex++) { csvPrinter.print(null); } csvPrinter.print(buildCellValue(csvCell)); } csvPrinter.println(); } rowCache.clear(); } catch (IOException e) { throw new ExcelGenerateException(e); } } private String buildCellValue(CsvCell csvCell) { switch (csvCell.getCellType()) { case STRING: case ERROR: return csvCell.getStringCellValue(); case NUMERIC: Short dataFormat = null; String dataFormatString = null; if (csvCell.getCellStyle() != null) { dataFormat = csvCell.getCellStyle().getDataFormat(); dataFormatString = csvCell.getCellStyle().getDataFormatString(); } if (csvCell.getNumericCellType() == NumericCellTypeEnum.DATE) { if (csvCell.getDateValue() == null) { return null; } // date if (dataFormat == null) { dataFormatString = DateUtils.defaultDateFormat; dataFormat = csvWorkbook.createDataFormat().getFormat(dataFormatString); } if (dataFormatString == null) { dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat); } return NumberDataFormatterUtils.format(BigDecimal.valueOf( DateUtil.getExcelDate(csvCell.getDateValue(), csvWorkbook.getUse1904windowing())), dataFormat, dataFormatString, csvWorkbook.getUse1904windowing(), csvWorkbook.getLocale(), csvWorkbook.getUseScientificFormat()); } else { if (csvCell.getNumberValue() == null) { return null; } //number if (dataFormat == null) { dataFormat = BuiltinFormats.GENERAL; dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat); } if (dataFormatString == null) { dataFormatString = csvWorkbook.createDataFormat().getFormat(dataFormat); } return NumberDataFormatterUtils.format(csvCell.getNumberValue(), dataFormat, dataFormatString, csvWorkbook.getUse1904windowing(), csvWorkbook.getLocale(), csvWorkbook.getUseScientificFormat()); } case BOOLEAN: return csvCell.getBooleanValue().toString(); case BLANK: return StringUtils.EMPTY; default: return null; } } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvWorkbook.java
package com.alibaba.excel.metadata.csv; import java.io.IOException; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.Locale; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import org.apache.commons.compress.utils.Lists; import org.apache.poi.ss.SpreadsheetVersion; import org.apache.poi.ss.formula.EvaluationWorkbook; import org.apache.poi.ss.formula.udf.UDFFinder; import org.apache.poi.ss.usermodel.CellReferenceType; import org.apache.poi.ss.usermodel.CellStyle; import org.apache.poi.ss.usermodel.CreationHelper; import org.apache.poi.ss.usermodel.DataFormat; import org.apache.poi.ss.usermodel.Font; import org.apache.poi.ss.usermodel.Name; import org.apache.poi.ss.usermodel.PictureData; import org.apache.poi.ss.usermodel.Row.MissingCellPolicy; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.SheetVisibility; import org.apache.poi.ss.usermodel.Workbook; /** * csv workbook * * @author Jiaju Zhuang */ @Getter @Setter @EqualsAndHashCode public class CsvWorkbook implements Workbook { /** * output */ private Appendable out; /** * true if date uses 1904 windowing, or false if using 1900 date windowing. * <p> * default is false * */ private Boolean use1904windowing; /** * locale */ private Locale locale; /** * Whether to use scientific Format. * <p> * default is false */ private Boolean useScientificFormat; /** * data format */ private CsvDataFormat csvDataFormat; /** * sheet */ private CsvSheet csvSheet; /** * cell style */ private List<CsvCellStyle> csvCellStyleList; /** * charset. */ private Charset charset; /** * Set the encoding prefix in the csv file, otherwise the office may open garbled characters. * Default true. */ private Boolean withBom; public CsvWorkbook(Appendable out, Locale locale, Boolean use1904windowing, Boolean useScientificFormat, Charset charset, Boolean withBom) { this.out = out; this.locale = locale; this.use1904windowing = use1904windowing; this.useScientificFormat = useScientificFormat; this.charset = charset; this.withBom = withBom; } @Override public int getActiveSheetIndex() { return 0; } @Override public void setActiveSheet(int sheetIndex) { } @Override public int getFirstVisibleTab() { return 0; } @Override public void setFirstVisibleTab(int sheetIndex) { } @Override public void setSheetOrder(String sheetname, int pos) { } @Override public void setSelectedTab(int index) { } @Override public void setSheetName(int sheet, String name) { } @Override public String getSheetName(int sheet) { return null; } @Override public int getSheetIndex(String name) { return 0; } @Override public int getSheetIndex(Sheet sheet) { return 0; } @Override public Sheet createSheet() { assert csvSheet == null : "CSV repeat creation is not allowed."; csvSheet = new CsvSheet(this, out); return csvSheet; } @Override public Sheet createSheet(String sheetname) { assert csvSheet == null : "CSV repeat creation is not allowed."; csvSheet = new CsvSheet(this, out); return csvSheet; } @Override public Sheet cloneSheet(int sheetNum) { return null; } @Override public Iterator<Sheet> sheetIterator() { return null; } @Override public int getNumberOfSheets() { return 0; } @Override public Sheet getSheetAt(int index) { assert index == 0 : "CSV exists only in one sheet."; return csvSheet; } @Override public Sheet getSheet(String name) { return csvSheet; } @Override public void removeSheetAt(int index) { } @Override public Font createFont() { return null; } @Override public Font findFont(boolean bold, short color, short fontHeight, String name, boolean italic, boolean strikeout, short typeOffset, byte underline) { return null; } @Override public int getNumberOfFonts() { return 0; } @Override public int getNumberOfFontsAsInt() { return 0; } @Override public Font getFontAt(int idx) { return null; } @Override public CellStyle createCellStyle() { if (csvCellStyleList == null) { csvCellStyleList = Lists.newArrayList(); } CsvCellStyle csvCellStyle = new CsvCellStyle((short)csvCellStyleList.size()); csvCellStyleList.add(csvCellStyle); return csvCellStyle; } @Override public int getNumCellStyles() { return csvCellStyleList.size(); } @Override public CellStyle getCellStyleAt(int idx) { if (idx < 0 || idx >= csvCellStyleList.size()) { return null; } return csvCellStyleList.get(idx); } @Override public void write(OutputStream stream) throws IOException { csvSheet.close(); } @Override public void close() throws IOException { } @Override public int getNumberOfNames() { return 0; } @Override public Name getName(String name) { return null; } @Override public List<? extends Name> getNames(String name) { return null; } @Override public List<? extends Name> getAllNames() { return null; } @Override public Name createName() { return null; } @Override public void removeName(Name name) { } @Override public int linkExternalWorkbook(String name, Workbook workbook) { return 0; } @Override public void setPrintArea(int sheetIndex, String reference) { } @Override public void setPrintArea(int sheetIndex, int startColumn, int endColumn, int startRow, int endRow) { } @Override public String getPrintArea(int sheetIndex) { return null; } @Override public void removePrintArea(int sheetIndex) { } @Override public MissingCellPolicy getMissingCellPolicy() { return null; } @Override public void setMissingCellPolicy(MissingCellPolicy missingCellPolicy) { } @Override public DataFormat createDataFormat() { if (csvDataFormat != null) { return csvDataFormat; } csvDataFormat = new CsvDataFormat(locale); return csvDataFormat; } @Override public int addPicture(byte[] pictureData, int format) { return 0; } @Override public List<? extends PictureData> getAllPictures() { return null; } @Override public CreationHelper getCreationHelper() { return null; } @Override public boolean isHidden() { return false; } @Override public void setHidden(boolean hiddenFlag) { } @Override public boolean isSheetHidden(int sheetIx) { return false; } @Override public boolean isSheetVeryHidden(int sheetIx) { return false; } @Override public void setSheetHidden(int sheetIx, boolean hidden) { } @Override public SheetVisibility getSheetVisibility(int sheetIx) { return null; } @Override public void setSheetVisibility(int sheetIx, SheetVisibility visibility) { } @Override public void addToolPack(UDFFinder toopack) { } @Override public void setForceFormulaRecalculation(boolean value) { } @Override public boolean getForceFormulaRecalculation() { return false; } @Override public SpreadsheetVersion getSpreadsheetVersion() { return null; } @Override public int addOlePackage(byte[] oleData, String label, String fileName, String command) { return 0; } @Override public EvaluationWorkbook createEvaluationWorkbook() { return null; } @Override public CellReferenceType getCellReferenceType() { return null; } @Override public void setCellReferenceType(CellReferenceType cellReferenceType) { } @Override public Iterator<Sheet> iterator() { return null; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java
easyexcel-core/src/main/java/com/alibaba/excel/metadata/csv/CsvDataFormat.java
package com.alibaba.excel.metadata.csv; import java.util.List; import java.util.Locale; import java.util.Map; import com.alibaba.excel.constant.BuiltinFormats; import com.alibaba.excel.util.ListUtils; import com.alibaba.excel.util.MapUtils; import org.apache.poi.ss.usermodel.DataFormat; /** * format data * * @author Jiaju Zhuang */ public class CsvDataFormat implements DataFormat { /** * It is stored in both map and list for easy retrieval */ private final Map<String, Short> formatMap; private final List<String> formatList; /** * Excel's built-in format conversion. */ private final Map<String, Short> builtinFormatsMap; private final String[] builtinFormats; public CsvDataFormat(Locale locale) { formatMap = MapUtils.newHashMap(); formatList = ListUtils.newArrayList(); builtinFormatsMap = BuiltinFormats.switchBuiltinFormatsMap(locale); builtinFormats = BuiltinFormats.switchBuiltinFormats(locale); } @Override public short getFormat(String format) { Short index = builtinFormatsMap.get(format); if (index != null) { return index; } index = formatMap.get(format); if (index != null) { return index; } short indexPrimitive = (short)(formatList.size() + BuiltinFormats.MIN_CUSTOM_DATA_FORMAT_INDEX); index = indexPrimitive; formatList.add(format); formatMap.put(format, index); return indexPrimitive; } @Override public String getFormat(short index) { if (index < BuiltinFormats.MIN_CUSTOM_DATA_FORMAT_INDEX) { return builtinFormats[index]; } int actualIndex = index - BuiltinFormats.MIN_CUSTOM_DATA_FORMAT_INDEX; if (actualIndex < formatList.size()) { return formatList.get(actualIndex); } return null; } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false
alibaba/easyexcel
https://github.com/alibaba/easyexcel/blob/aae9c61ab603c04331333782eedd2896d7bc5386/easyexcel-core/src/main/java/com/alibaba/excel/cache/Ehcache.java
easyexcel-core/src/main/java/com/alibaba/excel/cache/Ehcache.java
package com.alibaba.excel.cache; import java.io.File; import java.util.ArrayList; import java.util.Optional; import java.util.UUID; import com.alibaba.excel.context.AnalysisContext; import com.alibaba.excel.util.FileUtils; import com.alibaba.excel.util.ListUtils; import lombok.extern.slf4j.Slf4j; import org.apache.commons.collections4.CollectionUtils; import org.ehcache.CacheManager; import org.ehcache.config.CacheConfiguration; import org.ehcache.config.builders.CacheConfigurationBuilder; import org.ehcache.config.builders.CacheManagerBuilder; import org.ehcache.config.builders.ResourcePoolsBuilder; import org.ehcache.config.units.EntryUnit; import org.ehcache.config.units.MemoryUnit; /** * Default cache * * @author Jiaju Zhuang */ @Slf4j public class Ehcache implements ReadCache { public static final int BATCH_COUNT = 100; /** * Key index */ private int activeIndex = 0; public static final int DEBUG_CACHE_MISS_SIZE = 1000; public static final int DEBUG_WRITE_SIZE = 100 * 10000; private ArrayList<String> dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); private static final CacheManager FILE_CACHE_MANAGER; private static final CacheConfiguration<Integer, ArrayList> FILE_CACHE_CONFIGURATION; private static final CacheManager ACTIVE_CACHE_MANAGER; private static final File CACHE_PATH_FILE; private final CacheConfiguration<Integer, ArrayList> activeCacheConfiguration; /** * Bulk storage data */ private org.ehcache.Cache<Integer, ArrayList> fileCache; /** * Currently active cache */ private org.ehcache.Cache<Integer, ArrayList> activeCache; private String cacheAlias; /** * Count the number of cache misses */ private int cacheMiss = 0; @Deprecated public Ehcache(Integer maxCacheActivateSize) { this(maxCacheActivateSize, null); } public Ehcache(Integer maxCacheActivateSize, Integer maxCacheActivateBatchCount) { // In order to be compatible with the code // If the user set up `maxCacheActivateSize`, then continue using it if (maxCacheActivateSize != null) { this.activeCacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Integer.class, ArrayList.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(maxCacheActivateSize, MemoryUnit.MB)) .build(); } else { this.activeCacheConfiguration = CacheConfigurationBuilder .newCacheConfigurationBuilder(Integer.class, ArrayList.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .heap(maxCacheActivateBatchCount, EntryUnit.ENTRIES)) .build(); } } static { CACHE_PATH_FILE = FileUtils.createCacheTmpFile(); FILE_CACHE_MANAGER = CacheManagerBuilder.newCacheManagerBuilder().with(CacheManagerBuilder.persistence(CACHE_PATH_FILE)).build( true); ACTIVE_CACHE_MANAGER = CacheManagerBuilder.newCacheManagerBuilder().build(true); FILE_CACHE_CONFIGURATION = CacheConfigurationBuilder .newCacheConfigurationBuilder(Integer.class, ArrayList.class, ResourcePoolsBuilder.newResourcePoolsBuilder() .disk(20, MemoryUnit.GB)).build(); } @Override public void init(AnalysisContext analysisContext) { cacheAlias = UUID.randomUUID().toString(); try { fileCache = FILE_CACHE_MANAGER.createCache(cacheAlias, FILE_CACHE_CONFIGURATION); } catch (IllegalStateException e) { //fix Issue #2693,Temporary files may be deleted if there is no operation for a long time, so they need // to be recreated. if (CACHE_PATH_FILE.exists()) { throw e; } synchronized (Ehcache.class) { if (!CACHE_PATH_FILE.exists()) { if (log.isDebugEnabled()) { log.debug("cache file dir is not exist retry create"); } FileUtils.createDirectory(CACHE_PATH_FILE); } } fileCache = FILE_CACHE_MANAGER.createCache(cacheAlias, FILE_CACHE_CONFIGURATION); } activeCache = ACTIVE_CACHE_MANAGER.createCache(cacheAlias, activeCacheConfiguration); } @Override public void put(String value) { dataList.add(value); if (dataList.size() >= BATCH_COUNT) { fileCache.put(activeIndex, dataList); activeIndex++; dataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT); } if (log.isDebugEnabled()) { int alreadyPut = activeIndex * BATCH_COUNT + dataList.size(); if (alreadyPut % DEBUG_WRITE_SIZE == 0) { log.debug("Already put :{}", alreadyPut); } } } @Override public String get(Integer key) { if (key == null || key < 0) { return null; } int route = key / BATCH_COUNT; ArrayList<String> dataList = activeCache.get(route); if (dataList == null) { dataList = fileCache.get(route); activeCache.put(route, dataList); if (log.isDebugEnabled()) { if (cacheMiss++ % DEBUG_CACHE_MISS_SIZE == 0) { log.debug("Cache misses count:{}", cacheMiss); } } } return dataList.get(key % BATCH_COUNT); } @Override public void putFinished() { if (CollectionUtils.isEmpty(dataList)) { return; } fileCache.put(activeIndex, dataList); } @Override public void destroy() { FILE_CACHE_MANAGER.removeCache(cacheAlias); ACTIVE_CACHE_MANAGER.removeCache(cacheAlias); } }
java
Apache-2.0
aae9c61ab603c04331333782eedd2896d7bc5386
2026-01-04T14:46:28.604473Z
false