【问题标题】:How to use a custom separator in generating csv file如何在生成 csv 文件时使用自定义分隔符
【发布时间】: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 之类的东西有什么具体原因吗?

标签: java csv supercsv


【解决方案1】:

发生这种情况是因为您的列标题与字段名称不匹配。

改变

 final String[] header = new String[] {"id:","name:","age:","Country"};

到

final String[] header = new String[] {"id","name","age","Country"};

要使自定义分隔符起作用,您需要使用 CsvPreference 指定相同的分隔符

    CsvPreference csvPreference = new CsvPreference.Builder('"', ':', "\r\n").build();
    ICsvBeanWriter beanWriter = new CsvBeanWriter(writer, csvPreference);

此外,您可以使用 Open CSV 生成相同的内容。不知道你遇到了什么问题。我可以使用冒号 (:) 作为分隔符来生成。请在下面找到示例。

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(stream);
    com.opencsv.CSVWriter writer = new com.opencsv.CSVWriter(outputStreamWriter,':', ICSVWriter.DEFAULT_QUOTE_CHARACTER,ICSVWriter.DEFAULT_ESCAPE_CHARACTER,ICSVWriter.DEFAULT_LINE_END);
    List<Employee> emps = generateDemoData();
    for (Employee emp : emps) {
        writer.writeNext(new String[]{emp.getName(),emp.getAge(),emp.getCountry()});
    }
    writer.flush();
    //byte[] bytes = stream.toByteArray();
    System.out.println("CSV Data\n"+new String(stream.toByteArray()));

【讨论】:

  • 我得到了这个 CSV 数据 "Pankaj, saha":":30": "Timber:Hups":":10":"USA",我得到的是:而不是逗号
  • 这不是你想要的吗?你的问题是where i can use custom separator other than comma which is colon(:)。如果您想保留逗号作为分隔符,请继续使用标准 csv 首选项CsvPreference.STANDARD_PREFERENCE
  • Pankaj, saha",":30", "Timber:Hups",":10","USA" => 我想要这种格式
  • 如果你使用 CsvPreference.STANDARD_PREFERENCE,你会得到如下。 id,name,age,Country1,"Pankaj, saha",:30,2,Timber:Hups,:10,USA
  • I want Pankaj, saha",":30", "Timber:Hups",":10","USA" => 这意味着当它遇到: 它会用双引号括起来
猜你喜欢
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-09
  • 1970-01-01
  • 2020-12-17
相关资源
最近更新 更多