简体   繁体   中英

How to write list of objects in a csv using opencsv CSVWriter in java

I am trying to write some data to csv. Here is what I am trying to do:

class Sample {

  private String id;
  private String type;
  private String name;
  private int value;
  
  // getter-setter
}

Implementation

import com.opencsv.CSVWriter;

...

// code snippet

List<String> ids = getIds();
List<Sample> result = new ArrayList<>();
for (String id : ids) {
  Sample sample = getSample(id);
  
  result.add(sample);

}

//write result to csv
CSVWriter csvWriter = new CSVWriter(new FileWriter(filePath), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER);

// Not sure what to do next here.



I couldn't find much on writing a list of instances to csv.

UPDATE:

I tried the below links and code as suggested by @Praveen, @dgg below in comments but I am getting empty csv file written.

public void writeToCsv(String filePath, String[] header, List<Sample> samples) throws IOException {

        try (FileWriter writer = new FileWriter(filePath)) {
            ColumnPositionMappingStrategy mappingStrategy = new ColumnPositionMappingStrategy();
            mappingStrategy.setType(Sample.class);
            mappingStrategy.setColumnMapping(header);

            StatefulBeanToCsv<Sample> beanToCsv = new StatefulBeanToCsvBuilder<Sample>(writer)
                    .withMappingStrategy(mappingStrategy)
                    .withSeparator('#')
                    .withQuotechar(CSVWriter.NO_QUOTE_CHARACTER)
                    .build();

            // todo: getting empty csv file. why? currently debugging.
            beanToCsv.write(samples);

        } catch (CsvRequiredFieldEmptyException e) {
            e.printStackTrace();
        } catch (CsvDataTypeMismatchException e) {
            e.printStackTrace();
        }
    }



You can use StatefulBeanToCsv to map a list of object to a csv file

try (FileWriter writer = new FileWriter("path/to/file.csv")) {
    ColumnPositionMappingStrategy mappingStrategy =  new ColumnPositionMappingStrategy();
    mappingStrategy.setType(Sample.class);

    String[] columns = { "Id", "Type", "Name", "Value" };
    mappingStrategy.setColumnMapping(columns);
    
    StatefulBeanToCsv beanWriter = new StatefulBeanToCsvBuilder(writer)
        .withMappingStrategy(mappingStrategy)
        .build();

    beanWriter.write(sampleList);
}

I actually found a better way of writing it using PrintWriter , where my bean gets directly added to csv by overriding toString() in java bean. Here is what I did:

 public void writeToCsv(List<Sample> sampleList, String header) throws IOException {
        PrintWriter writer = new PrintWriter("filepath/demo/sample.csv");
        writer.println(header);

        for (Sample sample : sampleList) {
            writer.println(sample.toString());
        }
        writer.close();
    }

Bean

class Sample {

  private String id;
  private String type;
  private String name;
  private int value;
  
  // getter-setter

  @Override
  public String toString(){
        StringBuilder dataBuilder = new StringBuilder();
        appendFieldValue(dataBuilder, id);
        appendFieldValue(dataBuilder, type);
        appendFieldValue(dataBuilder, name);
        appendFieldValue(dataBuilder, value);
        

        return dataBuilder.toString();
    }

    private void appendFieldValue(StringBuilder dataBuilder, String fieldValue) {
        if(fieldValue != null) {
            dataBuilder.append(fieldValue).append(",");
        } else {
            dataBuilder.append("").append(",");
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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