简体   繁体   中英

Read CSV files with known and unknown columns java

I'm wondering if there is a way to read csv files with known and unknown columns.

for example the column in the first csv file is: id, firstname, lastname, city, country the unknwon columns are city and country

the second csv file is:

id, firstname, lastname, phone number the unknwon column is phone number

The Object that I want to parse into is:

public class Person {

    Long id;
    String firstname;
    String lastname;

    Map<String,String> additionalInfo;

}

the additionalInfo map will contain as keys the 'unknown' columns and the values will be the row value in that column.

Any ideas?

Thanks.

OpenCSV allows you to do something similar to this using @CsvBindAndJoinByName annotation. Taken from the docs :

public class Demonstration {

   @CsvBindByName(column = "index")
   private String index;

   @CsvBindAndJoinByName(column = ".*", elementType = String.class)
   private MultiValuedMap<String, String> theRest;

   // Getters and setters go here
}

The same docs mention a caveat: you have to be careful not to have overlapping patterns if you have multiple @CsvBindAndJoinByName , otherwise the result is undefined.

Had the same situation, wanted to access the unknown column from a CSV file. Here is the solution-

`

public class CSVFileDTO {
@CsvBindByName
private String name;

@CsvBindAndJoinByName(column = ".*", elementType = String.class)
private MultiValuedMap<String, String> theRest;

} `

Way to access theRest column -

    List<CSVFileDTO> resultData;
    MultiValuedMap<String, String> multivaluedMap = resultData.get(0).getTheRest();
    Collection<Map.Entry<String, String>> entries = multivaluedMap.entries();

    for(Map.Entry<String, String> ent : multivaluedMap.entries()){
        entityList.add(ent.getKey());
    }

Check feature 9 of this https://github.com/ozlerhakan/poiji API for reading excel files.

public class MusicTrack {

@ExcelCellName("ID")
private String employeeId;

@ExcelCellName("AUTHOR")
private String author;

@ExcelCellName("NAME")
private String name;

@ExcelUnknownCells
private Map<String, String> unknownCells;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM