导出到 csv 时忽略 JSON 中字符串中的逗号

ignore commas within string in JSON when exporting to csv

我正在使用 Filesaver.js and json-export-excel.js 将 json 文件导出到 csv。当逗号分隔符在字符串中看到逗号时,它会导致列移动。

Plunker 演示

如何忽略字符串中的逗号?

<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 文件:

$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.",
  },
]

当前 CSV 输出(不需要):(注意:| 标记 csv 文件中的列)

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.         |                  |       

所需的 CSV 输出:

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.                          |  

对于Excel,您需要将值用引号引起来。 See this question.

json-export-excel.js 中,您会看到 _objectToString 方法将输出用引号引起来,但是因为 fieldValue 变量不是一个对象,所以在这个例子中永远不会调用它。

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);
}

如果您向其中添加 else statement 以将值括在引号中,CSV 将根据需要在 Excel 中打开。

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

Plunker