带有BOM字符集的Javascript CSV导出



所以我有下面的函数,我想看看我是否能够在生成时将默认字符集转换为BOM,我想解决excel中的乱码问题。

exportCSVFile(headers, items, fileTitle) {
if (headers) {
items.unshift(headers);
}
// console.log(items)
// Convert Object to JSON
var jsonObject = JSON.stringify(items);
var csv = this.convertToCSV(jsonObject);
var exportedFilenmae = fileTitle + '.csv' || 'export.csv';
var blob = new Blob([csv], { type: 'text/csv;charset=windows-1252;' });
if (navigator.msSaveBlob) { // IE 10+
navigator.msSaveBlob(blob, exportedFilenmae);
} else {
var link = document.createElement("a");
if (link.download !== undefined) { // feature detection
// Browsers that support HTML5 download attribute
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", exportedFilenmae);
link.style.visibility = 'hidden';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
}
}

解决方案是,使用UTF8 添加BOM

var blob = new Blob(["uFEFF"+csv], {
type: 'text/csv; charset=utf-18'
});

最新更新