2

My code below is printing the columns with the data. I tried putting escapeCsv method of StringEscapeUtils but comma does not still go from the name column.

builder.append("Code,CodeName,CodeDepartment");
builder.append(System.lineSeparator());
Set<Entry<String, CodeDetails>> entrySet = sorted.entrySet();
for(Entry<String, CodeDetails> entry : entrySet)
{
    builder.append(entry.getKey());
    builder.append(",");
    builder.append(entry.getValue().getCodeName());
    StringEscapeUtils.escapeCsv(entry.getValue().getCodeName());
    builder.append(",");
    builder.append(entry.getValue().getCodeDepartment());
}
tobsob
  • 602
  • 9
  • 22
Aria
  • 47
  • 6
  • from the [StringEscapeUtils javadoc](https://commons.apache.org/proper/commons-lang/javadocs/api-2.6/org/apache/commons/lang/StringEscapeUtils.html#escapeCsv(java.lang.String)) : "If the value contains a comma, newline or double quote, then the String value is returned enclosed in double quotes". It doesn't remove the comma – jhamon Oct 21 '19 at 07:21
  • 1
    Wouldn't this work: `.getCodeName().replace(",", "")`? – DevilsHnd - 退職した Oct 21 '19 at 07:44

1 Answers1

3

It doesn't look like you're using the result of escapeCsv. You should try something like:

builder.append(StringEscapeUtils.escapeCsv(entry.getValue().getCodeName()));

Also, as noted in the comments, this won't remove the comma - it will surround the string with double quotes, which is correct for strings with commas in CSV.

Logan Pickup
  • 2,294
  • 2
  • 22
  • 29
  • I tried but stil does not come in the name column as a whole Name it is now surrounded with double quotes in another column(CodeDepartment) – Aria Oct 21 '19 at 07:37
  • 1
    You might need to double-check all your entries. Your original code first printed the name column, then attempted to escape it - are you still printing both `entry.getValue().getCodeName()` and `StringEscapeUtils.escapeCsv(entry.getValue().getCodeName())`? You should only be printing the latter. – Logan Pickup Oct 21 '19 at 07:51