ignore commas within string in JSON when exporting to csv
Asked Answered
F

1

6

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.                          |  
Flatter answered 21/12, 2016 at 15:24 Comment(1)
did you tried to escape the separator?Douzepers
S
4

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

Spadix answered 21/12, 2016 at 21:56 Comment(3)
Thank you so much! it worked!! I tried console.logging "output" inside _objectToString function and the values still got logged (without the double quotes) even tho the function is not called?Flatter
@Jason I just tried to log object inside _objectToString and I'm not seeing anything. Have you changed the data?Spadix
i think I was logging the output from output += key + ':' + value + ' '... so i'm actually not logging objectFlatter

© 2022 - 2024 — McMap. All rights reserved.