javacsvopencsv

CSV-file with many tables


The csv file contains more than one table, it might look like this:

"Vertical Table 1"
,
"id","visits","downloads"
 1, 4324, 23
 2, 664, 42
 3, 73, 44
 4, 914, 8

"Vertical Table 2"
,
"id_of_2nd_tab","visits_of_2nd_tab","downloads_of_2nd_tab"
 1, 524, 3
 2, 564, 52
 3, 63, 84
 4, 814, 8

To read one table I use "HeaderColumnNameTranslateMappingStrategy" from opencsv which allows me to map the csv-table entries into a List of TableDataBean objects, as seen below:

HeaderColumnNameTranslateMappingStrategy<TableDataBean> strat = new HeaderColumnNameTranslateMappingStrategy<TableDataBean>();

CSVReader reader = new CSVReader(new FileReader(path), ',');
strat.setType(TableDataBean.class);
Map<String, String> map = new HashMap<String, String>();
map.put("Number of visits", "visits");
map.put("id", "id");
map.put("Number of downloads", "downloads");
strat.setColumnMapping(map);
CsvToBean<TableDataBean> csv = new CsvToBean<TableDataBean>();
List<TableDataBean> list = csv.parse(strat, reader);

This works fine for the first table, but when it cames to the second, the values and the attributes are mapped to the same attribute of the first table. The output for

for(TableDataBean bean : list){System.out.println(bean.getVisits());}

would look like this:

 4324
 664
 73
 914
 null
 null
 null
 visits_of_2nd_tab
 524
 564
 63
 814

I don't wanna split the file into many files containing each of them one table. So what do you suggest ? Is there any other Library that supports this format?


Solution

  • I've got it! I thought that the type of reader have to be of CSVReader. It actually turned out that I can feed the methode parse with any object inheriting from the Reader class.

    Now I can read the entire csv-file into a String, splitt it, pack each of the new Strings into a StringReader and than pass it to the parse methode.