Home > Back-end >  OpenCSV fields with commas
OpenCSV fields with commas

Time:09-28

I am creating a csv where fields may include commas. In java the writing is done with opencsv.

try (Writer fileWriter = Files.newBufferedWriter(Paths.get(filePath))) {

      CSVWriter csvWriter =
          new CSVWriter(
              fileWriter,
              ICSVWriter.DEFAULT_SEPARATOR,
              ICSVWriter.NO_QUOTE_CHARACTER,
              ICSVWriter.DEFAULT_ESCAPE_CHARACTER,
              ICSVWriter.DEFAULT_LINE_END);
      csvWriter.writeNext(headers);
      csvWriter.writeAll(rows);
    } catch (IOException e) {
      throw new IOException(e);
    }

So taking field like ["field, 1", "field, 2", "field, 3"] I would expect to get a column with "field, 1", "field, 2", "field, 3" but I am getting field", 1,field", 2,field", 3 .

In the actual the commas are gone when opening in excel and for expected the quotes would not be shown. I am not seeing any docs for this on opencsv.

CodePudding user response:

Everything looks good except the ICSVWriter.NO_QUOTE_CHARACTER. By passing NO_QUOTE_CHARACTER as the parameter you are asking OpenCSV to consider quotes as regular text in the file and that is what it is doing.

If you are confident that double quotes are going to be your quote character, you can change it to ICSVWriter.DEFAULT_QUOTE_CHARACTER

Finally your snippet looks like below:

try (Writer fileWriter = Files.newBufferedWriter(Paths.get(filePath))) {

  CSVWriter csvWriter =
      new CSVWriter(
          fileWriter,
          ICSVWriter.DEFAULT_SEPARATOR,
          ICSVWriter.DEFAULT_QUOTE_CHARACTER,
          ICSVWriter.DEFAULT_ESCAPE_CHARACTER,
          ICSVWriter.DEFAULT_LINE_END);
  csvWriter.writeNext(headers);
  csvWriter.writeAll(rows);
} catch (IOException e) {
  throw new IOException(e);
}
  • Related