[英]Proper data formatting for CSV export
I'm currently exporting data (on the client side) to CSV, with specific utf-8 encoding 我目前正在使用特定的utf-8编码将数据(在客户端)导出为CSV
var csvContent = "data:text/csv;charset=utf-8,";
arr.forEach(function(infoArray, index){
var dataString = infoArray.join(",");
csvContent += index < arr.length ? dataString+ "\n" : dataString;
});
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "data.csv");
document.body.appendChild(link);
link.click();
The data is in arr and looks like : 数据在arr中 ,看起来像:
[{'firstname':'John', 'surname':'Doe', 'city':'Paris'}, ... , {'firstname':'Johnny', 'surname':'Done', 'city':'Paris'}]
It works pretty well expect that when I'm importing the resulting file in Excel I have encoding error (É -> É for example), but when I open the file in Sublime Text everything looks fine. 它很好地期望当我在Excel中导入生成的文件时,我有编码错误(例如É - >É),但是当我在Sublime Text中打开文件时,一切看起来都很好。
Looks like you need to include the UTF-8 BOM (Byte-Order Mark) after the comma and before the start of the data. 看起来您需要在逗号之后和数据开始之前包含UTF-8 BOM(字节顺序标记) 。 Three-byte sequence: [0xEF, 0xBB, 0xBF]
. 三字节序列: [0xEF, 0xBB, 0xBF]
。
Microsoft compilers and interpreters, and many pieces of software on Microsoft Windows such as Notepad treat the BOM as a required magic number rather than use heuristics. Microsoft编译器和解释器以及Microsoft Windows上的许多软件(如记事本)将BOM视为必需的幻数而不是使用启发式。 These tools add a BOM when saving text as UTF-8, and cannot interpret UTF-8 unless the BOM is present, or the file contains only ASCII bytes. 这些工具在将文本保存为UTF-8时添加BOM,除非BOM存在,否则无法解释UTF-8,或者文件仅包含ASCII字节。
Check out these articles/posts for more info. 查看这些文章/帖子了解更多信息。
var personArr = [ { firstname: 'John', surname: 'Doe', city: 'Paris' }, // ... , { firstname: 'James', surname: 'Brown', city: 'Barnwell' } ]; var csvData = jsonToCsv({ data : personArr }); var downloadLinkEle = createDownloadLink(csvData, 'people.csv'); document.body.appendChild(downloadLinkEle); function createDownloadLink(content, filename, text) { text = text || filename; var link = document.createElement('a'); link.setAttribute('href', encodeURI(content)); link.setAttribute('download', filename); link.innerHTML = text; return link; } function jsonToCsv(opts) { var BOM = "\"; opts.data = opts.data || []; opts.columns = opts.columns || []; opts.delim = opts.delim || ','; opts.headers = opts.headers || [ 'text/csv', 'charset=utf-8' ]; if (opts.columns.length < 1 && opts.data.length > 0) { opts.columns = Object.keys(opts.data[0]); } return 'data:' + opts.headers.join(';') + ',' + BOM + [ opts.columns.join(opts.delim), opts.data.map(rec => opts.columns.map(col => rec[col]).join(opts.delim)).join('\\n') ].join('\\n'); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.