Sha*_*man 14 javascript csv unicode excel
我正在尝试使用javascript在客户端生成CSV文件.我已经按照这个stackoverflow问题的答案.我在内容中有unicode字符(在我的例子中是希伯来字符).
文件生成成功,但是当我在Excel中打开文件时 - 所有unicode字符都显示为有趣的字符.ASCII字符(英文和数字)很好地呈现.
奇怪的是,如果我在记事本中打开文件,unicode字符就会显示出来.所以我想这与Excel以及我保存文件的方式有关.
有任何想法吗?
Sha*_*man 33
按照杰克科尔的评论和这个问题,解决我的问题是\uFEFF
在文件的开头添加一个BOM前缀().
这是工作代码:
var csvContent = "...csv content...";
var encodedUri = encodeURI(csvContent);
var link = document.createElement("a");
link.setAttribute("href", "data:text/csv;charset=utf-8,\uFEFF" + encodedUri);
link.setAttribute("download","report.csv");
link.click();
Run Code Online (Sandbox Code Playgroud)
建议的解决方案并不适用于所有浏览器,但我找到了一种让它在所有浏览器中工作的方法(Chrome、Firefox、IE11 甚至 Edge,...不知道 IE9-10,因为我不知道不再可以访问它们)。
我必须使用外部库来编码encoding.js,并且它与unicode 配合得非常好(我可以在Excel 的CSV 导出中看到我的独角兽表情符号)。
所以这是代码
data = new TextEncoder('utf-16be').encode(csvContent);
// create a Blob object for the download
const blob = new Blob(['\uFEFF', data], {
type: 'text/csv;charset=utf-8';
});
// if we're using IE/Edge, then use different download call
if (typeof navigator.msSaveOrOpenBlob === 'function') {
navigator.msSaveOrOpenBlob(blob, filename);
} else {
// the next code will generate a temp <a /> tag that you can trigger a hidden click for it to start downloading
const link = document.createElement('a');
const csvUrl = URL.createObjectURL(blob);
link.textContent = 'download';
link.href = csvUrl;
link.setAttribute('download', filename);
// set the visibility hidden so that there is no effect on your web-layout
link.style.visibility = 'hidden';
// finally we will append the anchor tag and remove it after clicking it
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
Run Code Online (Sandbox Code Playgroud)
就是这样,它适用于IE / Edge / Chrome / Firefox