我有一个充满数据的对象。 现在我想创建带注释的类,允许我创建具有指定列顺序的CSV文件或任何通用解决方案。 我的数据表示有点复杂意味着它与对象列表。
例如:
class User {
public String name;
public int age;
List<Relatives> relativeList;
public User() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Relatives> getRelativeList() {
return relativeList;
}
public void setRelativeList(List<Relatives> relativeList) {
this.relativeList = relativeList;
}
}
class Relatives {
public int id;
public String name;
public void setId(int id) {
this.id = id;
}
public int getId() {
return id;
}
public void setName(String name) {
this.name= name;
}
public String getName() {
return name;
}
}
我想用填充此类对象的数据创建CSV文件。
例如
User user = new User();
user.setName("Jackson");
user.setAge(32);
List<Relatives> relativeList = new ArrayList<Relatives>();
Relatives relatives = new Relatives();
relatives.setId(110);
relatives.setName("father");
relativeList.add(relatives);
relatives = new Relatives();
relatives.setId(111);
relativ.add(relatives);
relativeList.setName("mother");
user.setRelativeList(relativeList);
我想创建像。
这样的CSV文字"name";"age";"relatives id1";"relatives name1","relatives id2";"relatives name2"
"Jackson";"30";"110";"father";"111";"mother"
如示例所述,如果我在relativeList中有3个元素,那么应该添加一个名为“relatives id3”和“relatives name3”的列。哪个是元素+子元素意味着亲戚+(id或name)。 除此之外,我想确定生成的CSV中列的顺序意味着 年龄 可以在 名称 <之前的第一列结算/强>
对于这方面的确切解决方案可能并不容易获得,但任何接近解决方案的人都非常感激并且会有所帮助。
答案 0 :(得分:1)
It's the List within the object that is the killer. OpenCSV has a BeanToCsv class to convert a list of objects into a CSV file but I doubt it works with Collections (never tried it though). You can still use it if you want to limit the number of relatives a person has. Then you create an intermediate class that has the raw data fields with a constructor that takes your User class. Then using the BeanToCsv create the csv output you want.
However it sounds like you don't want to limit the user's number of relatives. So you can use openCSV to roll your own. Given a list of users objects you will have to do four things:
1. Determine the largest number of relatives the user has in your list.
2. Create a String array with the header values using the value from #1 to determine how many relative name and id columns to put. Once that is done create a List<String []> and put the array in the list.
3. Create a helper class to convert a User into a String array. Pass in the value from #1 so if you have fewer relatives than max you can pad with empty strings or null (your choice). Using this loop through the list of user objects converting each user to an array of strings and add that array to the the list created in #2.
4. Using the CSVWriter in openCsv call the writeAll method passing in the list you created and populated in steps 2 and 3.
Good luck
:)