I have created a MappingsBean class where all the columns of the CSV file are specified. Next I parse XML files and create a list of mappingbeans. Then I write that data int
The following works for me to map a POJO to a CSV file with custom column positioning and custom column headers (tested with opencsv-5.0) :
public class CustomBeanToCSVMappingStrategy extends ColumnPositionMappingStrategy {
@Override
public String[] generateHeader(T bean) throws CsvRequiredFieldEmptyException {
String[] headersAsPerFieldName = getFieldMap().generateHeader(bean); // header name based on field name
String[] header = new String[headersAsPerFieldName.length];
for (int i = 0; i <= headersAsPerFieldName.length - 1; i++) {
BeanField beanField = findField(i);
String columnHeaderName = extractHeaderName(beanField); // header name based on @CsvBindByName annotation
if (columnHeaderName.isEmpty()) // No @CsvBindByName is present
columnHeaderName = headersAsPerFieldName[i]; // defaults to header name based on field name
header[i] = columnHeaderName;
}
headerIndex.initializeHeaderIndex(header);
return header;
}
private String extractHeaderName(final BeanField beanField) {
if (beanField == null || beanField.getField() == null || beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class).length == 0) {
return StringUtils.EMPTY;
}
final CsvBindByName bindByNameAnnotation = beanField.getField().getDeclaredAnnotationsByType(CsvBindByName.class)[0];
return bindByNameAnnotation.column();
}
}
Pojo
Column Positioning in the generated CSV file:
@CsvBindByPositionHeader name in the generated CSV file:
@CsvBindByName, the generated header will be as per the annonationIf the field doesn't have @CsvBindByName, then the generated header will be as per the field name
@Getter @Setter @ToString
public class Pojo {
@CsvBindByName(column="Voucher Series") // header: "Voucher Series"
@CsvBindByPosition(position=0)
private String voucherSeries;
@CsvBindByPosition(position=1) // header: "salePurchaseType"
private String salePurchaseType;
}
Using the above Custom Mapping Strategy:
CustomBeanToCSVMappingStrategy mappingStrategy = new CustomBeanToCSVMappingStrategy<>();
mappingStrategy.setType(Pojo.class);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.withMappingStrategy(mappingStrategy)
.build();
beanToCsv.write(pojoList);