我有一个将数组转换为csv文件的函数。它在逗号上分隔,但是当数组的某个值中有逗号时,它也会在那里分隔。我试图用引号括起逗号并逃避它,但它仍然打破了csv。关于如何分离逗号而不是从数组值中分离的任何想法?
project(':a-subproject').buildDir
以下是以csvArray创建的数据示例:
convertArrayOfObjectsToCSV: function(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;
data = args.data || null;
if (data == null || !data.length) {
return null;
}
columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';
keys = Object.keys(data[0]);
result = '';
result += keys.join(columnDelimiter);
result += lineDelimiter;
data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter;
result += item[key];
ctr++;
});
result += lineDelimiter;
});
return result;
},
downloadCSV: function(args) {
var data, filename, link, csvArray;
csvArray = ids.map(function(id) {
return {
'id': id.id,
'image': id.image,
'desc': id.desc
};
});
var csv = utilities.convertArrayOfObjectsToCSV({
data: csvArray
});
if (csv == null) return;
filename = args.filename || 'export.csv';
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
data = encodeURI(csv);
link = document.createElement('a');
link.setAttribute('href', data);
link.setAttribute('download', filename);
link.click();
}
};
答案 0 :(得分:2)
更改如何将文字写入结果
data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter;
result += "\"" + item[key].replace(/"/g, '\\"') + "\"";
ctr++;
});
result += lineDelimiter;
});
只需在引号之间添加文字即可解决此问题。