I need to export data in csv, using a dto that I previously used as import of a csv file, where the expected output format is:
name;parent1;parent2;...;parentN
and the header would be:
name;parents
where parents would cover all the N values that represent the parents of the format above.
During the import to be able to read such a file I had to create the dto (MyDataParentsImport) in this way:
@CsvBindByPosition(position = 0, required = true)
private String name;
@CsvBindAndJoinByPosition(position = "1-", elementType = String.class, mapType = ArrayListValuedHashMap.class, required = false)
private MultiValuedMap<Integer, String> mapParentsNames;
the import works as a charm, but when I try to export in csv using the same DTO, openCSV looses part of the data present in mapParentsNames. Sometimes if the map contains 3 parents, the csv output contains only 1 or 2 parents.
To add data in the Map I use this method:
private MultiValuedMap<Integer, String> convertToMap(List<String> names, int startingKey) {
MultiValuedMap<Integer, String> pairs = new ArrayListValuedHashMap<>();
if (names != null) {
int key = startingKey;
for (String name : names) {
List<String> localNames = new ArrayList<>();
localNames.add(name);
pairs.putAll(key, localNames);
key++;
}
}
return pairs;
}
I write the CSV file in this way:
FileWriter writer = new FileWriter(file);
writer.append(MyDataHeader.getHeader() + "\n");
StatefulBeanToCsv<MyDataParentsImport> beanToCsv = new StatefulBeanToCsvBuilder<MyDataParentsImport>(writer)
.withSeparator(BulkImportConstants.CUSTOM_SEPARATOR)
.withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
.build();
beanToCsv.write(myData);
where myData is a list of object of type of the dto I described before (MyDataParentsImport).
I'm using openCSV 5.9.
EDIT:
I did more tests: if myData is a list of one element, the export is correct, no parent missing.