使用 Unicode 字符通过 JavaScript 为 Excel 生成 CSV

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18249290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:12:30  来源:igfitidea点击:

Generate CSV for Excel via JavaScript with Unicode Characters

javascriptexcelcsvunicode

提问by Shay Friedman

I am trying to generate a CSV file on the client side using javascript. I've followed the answer on this stackoverflow question. I have unicode characters in the content (Hebrew characters in my case).

我正在尝试使用 javascript 在客户端生成一个 CSV 文件。我已经按照这个 stackoverflow question 的答案进行操作。我的内容中有 unicode 字符(在我的例子中是希伯来字符)。

The file generation succeeds, however when I open the file in Excel - all the unicode characters are shown as funny characters. ASCII characters (English and numbers) are presented well.

文件生成成功,但是当我在 Excel 中打开文件时 - 所有 unicode 字符都显示为有趣的字符。ASCII 字符(英文和数字)显示良好。

The weird thing is that if I open the file in notepad, the unicode characters show well. So I guess this has something to do with Excel and the way I'm saving the file.

奇怪的是,如果我在记事本中打开文件,unicode 字符显示得很好。所以我想这与 Excel 以及我保存文件的方式有关。

Any ideas?

有任何想法吗?

回答by Shay Friedman

Following Hyman Cole's comment and this question, what fixed my problem was adding a BOM prefix (\uFEFF) to the beginning of the file.

按照 Hyman Cole 的评论和这个问题,解决我的问题是\uFEFF在文件开头添加 BOM 前缀 ( )。

This is the working code:

这是工作代码:

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();

回答by Ga???

On a Node/Express server, I tried Shay's answer but I was getting an error for invalid characters in my header. Instead, I added the \uFEFFto the beginning of the reply body and it worked.

在 Node/Express 服务器上,我尝试了 Shay 的回答,但我的标题中出现无效字符错误。相反,我将 加到\uFEFF回复正文的开头并且它起作用了。

app.get('/', function (req, res) {
    var csv = Papa.unparse(...);
    res.set({
       'Content-Type': 'text/csv; charset=UTF-8',
       'Content-Disposition': 'attachment; filename="file.csv"',
    });
    res.send('\uFEFF' + csv)
})

回答by ghiscoding

The suggested solution didn't work with all browsers, but I found a way to get it working in all browsers (Chrome, Firefox, IE11 and even Edge, ... don't know about IE9-10 since I don't have access to them anymore).

建议的解决方案不适用于所有浏览器,但我找到了一种方法让它在所有浏览器(Chrome、Firefox、IE11 甚至 Edge,...不知道 IE9-10,因为我没有不再访问它们)。

I have to use an external library to encode encoding.jsand it works amazingly well with unicode (I can see my unicorn emoji in my CSV export in Excel).

我必须使用外部库来编码encoding.js,它与 unicode 一起工作得非常好(我可以在 Excel 的 CSV 导出中看到我的独角兽表情符号)。

So here's the code

所以这是代码

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';
});

// when using IE/Edge, then use different download call
if (typeof navigator.msSaveOrOpenBlob === 'function') {
  navigator.msSaveOrOpenBlob(blob, filename);
} else {
  // this trick 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 there is no effect on your web-layout
  link.style.visibility = 'hidden';

  // this part will append the anchor tag and remove it after automatic click
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

and that's it, it works in IE / Edge / Chrome / Firefox

就是这样,它适用于 IE / Edge / Chrome / Firefox

enter image description here

在此处输入图片说明