Converter
This chapter introduces how to use custom converters when writing data.
Overview
Fesod supports custom data converters for write operations. You can transform Java field values before they are written to Excel cells, enabling custom formatting, encryption, or any data transformation logic.
Per-Field Converter
Overview
Apply a converter to a specific field using the @ExcelProperty(converter = ...) annotation.
Converter
public class CustomStringStringConverter implements Converter<String> {
@Override
public Class<?> supportJavaTypeKey() {
return String.class;
}
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return CellDataTypeEnum.STRING;
}
@Override
public String convertToJavaData(ReadConverterContext<?> context) {
return "Custom: " + context.getReadCellData().getStringValue();
}
@Override
public WriteCellData<?> convertToExcelData(WriteConverterContext<String> context) {
return new WriteCellData<>("Custom: " + context.getValue());
}
}
POJO Class
@Getter
@Setter
@EqualsAndHashCode
public class ConverterData {
@ExcelProperty(value = "String Title", converter = CustomStringStringConverter.class)
private String string;
@DateTimeFormat("yyyy-MM-dd HH:mm:ss")
@ExcelProperty("Date Title")
private Date date;
@NumberFormat("#.##%")
@ExcelProperty("Number Title")
private Double doubleData;
}
Code Example
@Test
public void converterWrite() {
String fileName = "converterWrite" + System.currentTimeMillis() + ".xlsx";
FesodSheet.write(fileName, ConverterData.class)
.sheet()
.doWrite(data());
}
Global Converter Registration
Overview
Register a converter at the builder level to apply it to ALL fields matching the Java type and Excel type. This is useful when you want the same transformation applied globally without annotating each field.
For ordinary XLSX/XLS writes, global converter lookup uses the Java type and a null Excel type key. Use the following variant of the converter above. The returned WriteCellData still determines the output cell type; returning null here only changes the lookup key.
public class GlobalStringWriteConverter extends CustomStringStringConverter {
@Override
public CellDataTypeEnum supportExcelTypeKey() {
return null;
}
}
For CSV writing and reading string cells, register the original CustomStringStringConverter, which returns CellDataTypeEnum.STRING.
Code Example
@Test
public void globalConverterWrite() {
String fileName = "globalConverterWrite" + System.currentTimeMillis() + ".xlsx";
FesodSheet.write(fileName, DemoData.class)
.registerConverter(new GlobalStringWriteConverter())
.sheet()
.doWrite(data());
}
Converter Resolution Priority
When multiple converters could apply to a field, Fesod resolves them in this order:
- Field-level converter (
@ExcelProperty(converter = ...)) — highest priority - Builder-level converter (
.registerConverter(...)) with a matching lookup key - Built-in default converter — lowest priority