提问者:小点点

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


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

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

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

共1个答案

匿名用户

对于Excel,您需要用引号将值换行。请参阅此问题。

json-export-excel. js中,您将看到_objectToString方法将输出包装在引号中,但由于field dValue变量不是对象,因此在此示例中从未调用过。

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语句以将值用引号括起来,则CSV将按需在Excel中打开。

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

普朗克