Skip to main content

Custom Converter

This chapter introduces how to create and register custom converters for both read and write operations.

Overview​

Fesod provides a Converter interface that allows you to define custom data transformation logic. Converters can be registered per-field (via annotation) or globally (via builder), and work for both reading and writing.

Creating a Custom Converter​

Converter Implementation​

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());
}
}

Per-Field vs. Global Registration​

ApproachScopeHow
Per-fieldSingle field only@ExcelProperty(converter = MyConverter.class)
GlobalAll fields matching Java type + Excel type.registerConverter(new MyConverter()) on the builder

Converter Resolution Priority​

  1. Field-level converter (@ExcelProperty(converter = ...)) — highest priority
  2. Builder-level converter (.registerConverter(...)) with a matching lookup key
  3. Built-in default converter — lowest priority

Global Registration Example​

Write with Global Converter​

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.

@Test
public void customConverterWrite() {
String fileName = "customConverterWrite" + System.currentTimeMillis() + ".xlsx";

FesodSheet.write(fileName, DemoData.class)
.registerConverter(new GlobalStringWriteConverter())
.sheet()
.doWrite(data());
}

Read with Global Converter​

@Test
public void customConverterRead() {
String fileName = "path/to/demo.xlsx";

FesodSheet.read(fileName, DemoData.class, new DemoDataListener())
.registerConverter(new CustomStringStringConverter())
.sheet()
.doRead();
}