简体   繁体   English

读取具有已知和未知列的 CSV 文件 java

[英]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.我想知道是否有办法读取具有已知和未知列的 csv 文件。

for example the column in the first csv file is: id, firstname, lastname, city, country the unknwon columns are city and country例如,第一个 csv 文件中的列是: id, firstname, lastname, city, country unknwon 列是城市和国家

the second csv file is:第二个csv文件是:

id, firstname, lastname, phone number the unknwon column is phone number id, firstname, lastname, phone number unknwon 列是电话号码

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. additionalInfo 映射将包含“未知”列作为键,值将是该列中的行值。

Any ideas?有任何想法吗?

Thanks.谢谢。

OpenCSV allows you to do something similar to this using @CsvBindAndJoinByName annotation. OpenCSV 允许您使用@CsvBindAndJoinByName注释执行类似的@CsvBindAndJoinByName 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.相同的文档提到了一个警告:如果你有多个@CsvBindAndJoinByName ,你必须小心不要有重叠的模式,否则结果是未定义的。

Had the same situation, wanted to access the unknown column from a CSV file.有同样的情况,想从 CSV 文件访问未知列。 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.检查此https://github.com/ozlerhakan/poiji API 的功能 9 以读取 excel 文件。

public class MusicTrack {

@ExcelCellName("ID")
private String employeeId;

@ExcelCellName("AUTHOR")
private String author;

@ExcelCellName("NAME")
private String name;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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