This creates a MappingStrategy for use with OpenCSV (specifically tested for generating a CSV from beans) which does the following:
- Preserves the column name casing in the
@CsvBindByName
annotation - Adds a
@CsvBindByNameOrder
annotation you can apply to the bean class to define the order of the columns.
- Any field not included in the order, but is still annotated with
@CsvBindName
will still be included AFTER all the columns that have a defined order. Those remaining columns will be added in alphabetical order (this is the default behavior of theHeaderColumnNameMappingStrategy
)
- Overrides the converter used with
@CsvDate
to use a custom converter that adds support for the java time api (LocalDate
,LocalTime
, andLocalDateTime
are tested)
Annotate your bean with something like...
@CsvBindByNameOrder({"Foo","Bar"})
public class MyBean {
@CsvBindByName(column = "Foo")
private String foo;
@CsvBindByName(column = "Bar")
private String bar;
// getter/setters omitted for brevity
}
Setup your writer...
List<MyBean> beans = new ArrayList();
MyBean bean = new MyBean();
bean.setFoo("fooit");
bean.setBar("barit");
beans.add(bean);
StringWriter writer = new StringWriter();
StatefulBeanToCsv<MyBean> csvWriter = new StatefulBeanToCsvBuilder<MyBean>(writer)
.withApplyQuotesToAll(false)
.withMappingStrategy(new HeaderColumnNameAndOrderMappingStrategy<>(MyBean.class))
.build();
csvWriter.write(beans);
return writer.toString();
Results
With the above you should get something like...
Foo,Bar
fooit,barit
Thanks @ammmze and @nerdmeeting , exactly what I needed!