Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Apache Commons CSV - case insensitive headers?

Is there a built-in feature in Apache CSV implementation to ignore header case when reading csv?

Some time ago we have implemented utility for converting CSV export files to SQL. For that we have choosen Apache CSV. Everything was perfectly fine until now, but yet now we've got a change request.

All CSV files we process must contain headers and now we should read those headers in case insensitive way, so our users don't have to put their effort in it and watch if CSV they created follows our header case requirments.

Code sample:

for (CSVRecord record : subsidiaryRows) {
    String name = record.get(Data.NAME));

where Data.NAME is

public static final String NAME = "Name";

And the problem obviously raises when the user uses "name" as column header in his CSV instead of "Name" with capital "N".

I have followed both the API and source but couldn't find anything. Is there a way how to force the CSVRecord use CaseInsensitiveMap for its mapping or anything similiar?

like image 430
Kousalik Avatar asked Apr 28 '15 05:04

Kousalik


2 Answers

This feature was added to Apache Commons CSV 1.3 as CSV-159

Committed revision 1708685.

like image 159
Gary Gregory Avatar answered Sep 25 '22 14:09

Gary Gregory


I think you have to handle csv headers to your convenience, before you parse CSV file with apache-commons-csv, you can do this with RandomAccessFile to overwrite case in first line (headers)

//convert headers to my 'known' format (ie: lowercase)
RandomAccessFile raf = new RandomAccessFile("C:\\test.csv", "rw");
String firstLine = raf.readLine();
raf.seek(0);
raf.writeBytes(firstLine.toLowerCase());

//your normal process to parse CSV with commons csv

PS: I think is very difficult to achieve this in some other way, since is a closed api (every class is final and the headers mapping returns a copy of the internal headers map)

like image 29
yamilmedina Avatar answered Sep 21 '22 14:09

yamilmedina