@csvbindbyname-使用备用列名绑定列

pdtvr36n  于 2021-09-13  发布在  Java
关注(0)|答案(1)|浏览(633)

我有两个csv源来读取数据。两个csv文件提供相同的数据,但名称或列位置不同。有没有办法在@csvbindbyname中加上“或”。例如,两个文件的标题如下
csv 1-rollno,studentname,class,age,primarylanguage,projectname
csv 2-姓名、班级、基本语言、注册号、年龄、项目、出席率
我必须在同一个pojo中读取两个csv文件信息。

public class StudentInfo{
@CsvBindByName(column = "RollNo")
private String rollNo;

@CsvBindByName(column = "StudentName")
private String studentName;

@CsvBindByName(column = "PrimaryLanguage")
private String primaryLanguage;

@CsvBindByName(column = "Class")
private String class;

@CsvBindByName(column = "ProjectName")
private String projectName;

@CsvBindByName(column = "Age")
private String age;

//getters and setters
}

或者有没有其他方法来实现这一点。如果我只使用一种csv头格式,那么我的代码工作正常。谢谢

gev0vcfq

gev0vcfq1#

Profiles 在opencsv中解决了这个问题,但它仅在5.4中可用。
请参阅有关的文档 Profiles 下面是官方文档中的代码片段。

public class Person {
  @CsvBindByNames({
    @CsvBindByName(column = "last name"),
    @CsvBindByName(profiles = {"customer 2", "customer 5"})
  })
  private String surname;

  @CsvBindByNames({
    @CsvBindByName,
    @CsvBindByName(column = "first name", profiles = "customer 1"),
    @CsvBindByName(column = "given name", profiles = "customer 2")
  })
  private String name;

  @CsvIgnore(profiles = "customer 2")
  @CsvBindByName(column = "middle initial")
  private char initial;

  @CsvBindByName(column = "salary", profiles = "customer 1")
  @CsvBindByName(column = "annual salary", profiles = "customer 2")
  @CsvNumber(value = "#0.00", profiles = "customer 1")
  @CsvNumber(value = "0.0#E0", profiles = "customer 2")
  private float salaryInUSD;

  @CsvBindByName(column = "height")
  @CsvNumbers({
    @CsvNumber("000"),
    @CsvNumber(value = "000cm", profiles = "customer 2")
  })
  private int heightInCentimeters

  // Accessor methods go here.
}

// Now, the profile can be used in the builder parse, see below.

List<Person> beans = new CsvToBeanBuilder<Person>(inputfile)
  .withProfile("customer 1")
  .withType(Person.class)
  .build()
  .parse();

相关问题