由于要做一个 UserScript 用到了这个功能,便顺便记录下来。
数组结构
var data = [
{
"title" :value,
"href" : value
},
...
]
生成 CSV 字符串
function convertArrayOfObjectsToCSV(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;
}
生成 CSV 文件,并下载
function downloadCSV(args) {
var data, filename, link;
var csv = convertArrayOfObjectsToCSV({
data: data
});
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();
}
代码来源:https://halistechnology.com/2015/05/28/use-javascript-to-export-your-data-as-csv/