【问题标题】:ignore commas within string in JSON when exporting to csv导出到 csv 时忽略 JSON 字符串中的逗号
【发布时间】:2017-05-07 01:58:08
【问题描述】:

我正在使用 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.                          |  

【问题讨论】:

  • 您是否尝试过转义分隔符?

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


【解决方案1】:

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

【讨论】:

  • 非常感谢!有效!!我在 _objectToString 函数中尝试了 console.logging “输出”,即使没有调用该函数,值仍然被记录(没有双引号)?
  • @Jason 我只是尝试在_objectToString 中记录object,但我什么也没看到。您是否更改了数据?
  • 我想我正在从output += key + ':' + value + ' ' 记录output...所以我实际上没有记录object
猜你喜欢
  • 2011-10-10
  • 1970-01-01
  • 2015-09-05
  • 2018-05-20
  • 2021-01-03
  • 2021-08-06
  • 2012-05-23
  • 1970-01-01
  • 2021-07-09
相关资源
最近更新 更多