导出到csv

时间:2016-12-21 15:24:38

标签: javascript angularjs json export-to-csv filesaver.js

我使用Filesaver.jsjson-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.                          |  

1 个答案:

答案 0 :(得分:2)

对于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