【发布时间】:2021-07-17 05:59:25
【问题描述】:
我正在尝试生成一个 CSV,我可以在其中使用逗号以外的自定义分隔符,即冒号 (:),这意味着如果字符串包含冒号 (:),则在生成 csv 时,它应该在它们周围附加双引号。我使用了 apache commons api,但我无法解决这个目的。我遇到了一个新的 api,它是 super csv,我正在尝试使用它来生成 csv,下面是我尝试过的代码
public class SuperCsvWriter{
public static void main(String ar[]){
List<Employee> emps = generateDemoData();
StringWriter writer = new StringWriter();
ICsvBeanWriter beanWriter = new CsvBeanWriter(writer,CsvPreference.STANDARD_PREFERENCE);
final String[] header = new String[] {"id:","name:","age:","Country"};
final CellProcessor[] processors = getProcessors();
beanWriter.writeHeader(header);
for(Employee emp: emps){
beanWriter.write(emp,header,processors);
}
beanWriter.close();
Sytem.out.println("CSV Data\n"+writer.toString());
}
private static CellProcessor[] getProcessors(){
final CellProcessor[] processors = new CellProcessor[]{new UniqueHashCode(),//ID
new NotNull(), //Name
new Optional(),//Age
new Optional() //Country
};
return processors;
}
private static List<Employee> generateDemoData(){
List<Employee> empsToAdd = new ArrayList<Employee>();
Employee emp = new Employee();
emp.setId("1");
emp.setName("Pankaj, saha");
emp.setAge(":30");
Employee emp1 = new Employee();
emp1.setId("2");
emp1.setName("Timber:Hups");
emp1.setAge(":10");
emp1.setCountry("USA");
empsToAdd.add(emp);
empsToAdd.add(emp1);
return empToAdd;
My bean class
public class Employee{
private String id;
private String name;
private String age;
private String country;
..........................
Now my requirement is whenever csv will be generated it should print like below
"id:","name:","age:",country
1,"pankaj,saha",":30",
2,"Timber:Hups",":10",USA
But here i am getting exception
Exception in thread "main" org.supercsv.exception.SuperCsvReflectionException: unable to find
greater for field id: in class com.test.Employee - check that the context = null
不知道为什么我需要在 bean 类中添加冒号,以及使用 super csv 实现自定义分隔符的方法是什么
【问题讨论】:
-
请注意,Super CSV 似乎已被放弃。使用它而不是 Jackson CSV 之类的东西有什么具体原因吗?