ignore commas within string in JSON when exporting to csv

7.6k views Asked by At

I'm exporting json files to csv using Filesaver.js and json-export-excel.js. The comma separator is causing the columns to shift when it sees a comma in the string.

Plunker Demo

How can i ignore commas found within string?

<button ng-json-export-excel data="data" report-fields="{name: 'Name', quote: 'Quote'}" filename ="'famousQuote'" separator="," class="purple_btn btn">Export to Excel</button>

JS File:

$scope.data = [
  {
    name: "Jane Austen",
    quote: "It isn\'t what we say or think that defines us, but what we do.",
  },
  {
    name: "Stephen King",
    quote: "Quiet people have the loudest minds.",
  },
]

Current CSV output (Not Desired): (Note: | marks the columns in csv file)

Name          Quote                                        
Jane Austen |  It isn't what we say or think that defines us|   but what we do.|
Stephen King|  Quiet people have the loudest minds.         |                  |       

Desired CSV output:

Name          Quote                                        
Jane Austen |  It isn't what we say or think that defines us, but what we do.|
Stephen King|  Quiet people have the loudest minds.                          |  
1

There are 1 answers

3
Jaydo On BEST ANSWER

For Excel, you need to wrap values in quotation marks. See this question.

In json-export-excel.js you'll see that the _objectToString method wraps the output in quotes but because the fieldValue variable isn't an object this is never called for this example.

function _objectToString(object) {
  var output = '';
  angular.forEach(object, function(value, key) {
    output += key + ':' + value + ' ';
  });

  return '"' + output + '"';
}

var fieldValue = data !== null ? data : ' ';

if fieldValue !== undefined && angular.isObject(fieldValue)) {
  fieldValue = _objectToString(fieldValue);
}

If you add an else statement to this to wrap the value in quotes, the CSV opens in Excel as desired.

} else if (typeof fieldValue === "string") {
  fieldValue = '"' + fieldValue + '"';
}  

Plunker