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
@CsvBindByNameannotation - Adds a
@CsvBindByNameOrderannotation 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
@CsvBindNamewill 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
@CsvDateto use a custom converter that adds support for the java time api (LocalDate,LocalTime, andLocalDateTimeare 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