0

I'm using CSVPrinter to create a CSV.

@Data
public class ExportRecord {

    String name;
    String email;
    String code;

    @Override
    public String toString() {
        return String.join(";",
                name,
                email,
                StringUtils.defaultString(code));   
    }

}
CSVFormat csvFormat = CSVFormat.EXCEL.builder()
                .setDelimiter(';')
                .setHeader(Arrays.stream(ExportHeader.values()).map(ExportHeader::getCsvHeader).toArray(String[]::new))
                .build();

try (CSVPrinter csvPrinter = new CSVPrinter(new FileWriter(csvToExport), csvFormat)) {
  for (ExportRecord exportRecord : exportRecords) {
    csvPrinter.printRecord(exportRecord);
  }
} catch (IOException e) {
    ...
}

This is working fine but it adds double quotes to the beginning and the end of the line. e.g.

header1;header2;header3
"string1;string2;string3"

How can I remove those?

Sven
  • 139
  • 2
  • 3
  • 12
  • What is `ExportRecord`? – Shawn Feb 28 '22 at 03:43
  • @Shawn Hi, I added the class ExportRecord. I have a list of exportRecords which contain data (coming from a native sql query). – Sven Feb 28 '22 at 04:09
  • 1
    Looks like `CSVPrinter#printRecord` takes one or more things, and you're only giving it one, with the delimiter in it, hence the quotes. – Shawn Feb 28 '22 at 05:01

1 Answers1

0

I tried an easier solution using PrintWriter and that solved it.

try (PrintWriter printWriter = new PrintWriter(csvToExport)) {
    String header = Arrays.stream(ExportHeader.values())
                    .map(ExportHeader::getCsvHeader)
                    .collect(joining(";"));
    printWriter.println(header);
    for (ExportRecord exportRecord : exportRecords) {
       printWriter.println(exportRecord.toString());
    }
} catch (IOException e) {
    ...
}
Sven
  • 139
  • 2
  • 3
  • 12