2

I have a list of objects that are instances of a number of sub-classes of a base class. I've been trying to write these objects out together into one CSV file.

Each class contains the fields of the base class and adds a couple of extra fields of its own.

What I am trying to achieve is to write out a csv having the base class fields first and then the columns coming from the rest of the sub-classes. This of course means that the sub-classes that don't contain a particular column name should have that field empty.

I have tried achieving this using OpenCSV and SuperCSV but have not managed to configure them to do this. Looking at the libraries code I am pretty sure OpenCSV will not do this. Using SuperCSV with Dozer I got multiple classes to write in one file but I can't get the empty columns in place where a class is missing a particular column field.

I can obviously write my own custom CSV writer to achieve this but I was wondering if anyone could help me reach a solution based off an existing CSV writer library.

Edit: SuperCSV code added below per commenter's request

private static final String[] FIELD_MAPPING = new String[] { "documentNumber", "lineOfBusiness", "clientId", "childClass1Field", };
private static final String[] FIELD_MAPPING2 = new String[] { "documentNumber", "lineOfBusiness", "clientId", "childClass2Field1", "childClass2Field2"};

public static void writeWithCsvBeanWriter(PrintWriter writer, List<ParentClass> documents) throws Exception {
    CsvDozerBeanWriter beanWriter = null;
    try {
        beanWriter = new CsvDozerBeanWriter(writer, CsvPreference.STANDARD_PREFERENCE);

        final String[] header = new String[] { "documentNumber", "lineOfBusiness", "clientId", "childClass1Field", "childClass2Field1", "childClass2Field2"};

        beanWriter.configureBeanMapping(ChildClass1.class, FIELD_MAPPING);
        beanWriter.configureBeanMapping(ChildClass2.class, FIELD_MAPPING2);

        final CellProcessor[] processors = new CellProcessor[] { new Optional(), new Optional(), new Optional(), new Optional() }
        final CellProcessor[] processors2 = new CellProcessor[] { new Optional(), new Optional(), new Optional(), new Optional(), new Optional() }

        beanWriter.writeHeader(header);

        for (final ParentClass document : documents) {
            if (document instanceof ChildClass1) {
                beanWriter.write(document, processors);
            } else {
                beanWriter.write(document, processors2);
            }
        }
    } finally {
        if (beanWriter != null) {
            beanWriter.close();
        }
    }
}
triadiktyo
  • 479
  • 2
  • 9

0 Answers0