javacsvsupercsv

Looking for a java CSV library that allows reading columns by name


Also, allows handling of long rows in a readable/easy manner, in writing them as well as in reading them.

I've looked into opencsv but it does not refer to elements in row in any sequential fashion, and supercsv does not allow looking into column by name but number only.

Another caveat - for which I need to be able to address columns by name - is that the number of columns is not constant, and only part of the column headers are constant, something like:

Name|Number|Color1|Color2......|Color67|   

where not all colors between 1 and 67 are present in any given CSV file.


Solution

  • I can't really speak to opencsv, but if you have a fixed number of fields you might be able to use the JavaBean binding to do something like this.

    Super CSV however, definitely supports reading and writing CSV rows by name using CsvBeanReader, CsvDozerBeanReader or CsvMapReader (and their writing equivalents).

    If you prefer to keep things simple and use a map (with the column name as key, and the column value as the value) then you could use CsvMapReader. There are examples on reading and writing with CsvMapReader on the Super CSV website.

    A reading example:

     ICsvMapReader mapReader = new CsvMapReader(
          new FileReader("foo.csv"), CsvPreference.EXCEL_PREFERENCE);
     try {
      final String[] headers = mapReader.getHeader(true);
      Map<String, String> row;
      while( (row = mapReader.read(headers)) != null) {
        for (String header : headers) {
          System.out.println(header + " is " + row.get(header));
        }
      }
    } finally {
      mapReader.close();
    }
    

    Writing is quite similar.