3

How to convert my bean MyClassCsv to a CSV file with the name of an optional column? The column 'title' must be contained or not in the CSV file.

The bean:

@Builder
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class MyClassCsv implements Serializable {
   
    private static final long serialVersionUID = -6476622625063619084L;

    @CsvBindByName(column = "id")
    private Integer id;

    @CsvBindByName(column = "name")
    private String name; 
    
    @CsvBindByName(column = "title")
    private String title; 
    
    ...
}

Write to CSV:

final Writer writer = new FileWriter(fileCsv.getPath());

try {
    final HeaderColumnNameMappingStrategy<HoteIncbCsv> strategy = new HeaderColumnNameMappingStrategy<>();
    strategy.setType(MyClassCsv.class);

    // **** optional mapped 'title'  ***** //
    if (!useTitle) {
        // ?????????
    }
    
    final StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer).withMappingStrategy(strategy).withSeparator(';').withApplyQuotesToAll(false).build();

    // Ecriture dans le fichier CSV de sortie
    beanToCsv.write(myClassCsv);

} finally {
    writer.close();
}
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
christo
  • 31
  • 2

1 Answers1

2

I know this is old post , but stumbled upon it while doing something similar, maybe somebody would need solution. HeaderColumnNameMappingStrategy has setIgnoredFields method that can be used in exactly that case. You can create more or less something like this to create strategy

private HeaderColumnNameMappingStrategy <MyClassCsv> createHeaderStrategy(boolean title) throws NoSuchFieldException {
    HeaderColumnNameMappingStrategy strategy = new HeaderColumnNameMappingStrategy<MyClassCsv >();
    strategy.setType(MyClassCsv.class);
    if(!title){
        MultiValuedMap<Class<?>, Field> ignore = new ArrayListValuedHashMap<Class<?>, Field>();
        ignore.put(MyClassCsv.class, MyClassCsv.class.getDeclaredField("title")) 
        strategy.ignoreFields(ignore);
    }
    return strategy 
}

This of course can be done better with some custom annotations to exclude more fields if needed, and eliminate need of potentially catching NoSuchFieldException exception.

Khobar
  • 486
  • 7
  • 20