【问题标题】:execCommand in internet explorer saves the csv file using USC-2 Little endian encoding, how to save it with UTF-8 format?Internet Explorer 中的 execCommand 使用 USC-2 Little endian 编码保存 csv 文件,如何以 UTF-8 格式保存?
【发布时间】:2014-08-20 10:06:01
【问题描述】:

execCommand 总是以 USC-2 little indian 格式保存 .csv 文件,但我希望它是 UTF-8 格式。此外,当我将文件名更改为 .txt 时,编码是正确的 UTF-8。如何实现 csv 文件的 UTF-8 编码?我确实尝试将字符集设置为 UTF-8,但它不起作用。

var oWin = window.open("about:blank", "_blank");
oWin.document.open("application/csv", "replace");
oWin.document.charset = "utf-8";
oWin.document.write(csvText);
oWin.document.close();
var success = oWin.document.execCommand('SaveAs', true, 'fileName.csv');
oWin.close();
alert(success);

生成的文件内容正确,但编码不是 UTF-8,因此 excel 无法识别列,整行显示在单列中。 生成的文件(fileNam.csv):

"Column One","Column Two","Column Three"
"row1 Col1","row1 Col2"
"row2 Col1","row2 Col2","row2 Col3"
"row3 Col1","row3 Col2","row3 Col3"

我想使用 javascript 并且专门针对 IE 来执行此操作。我知道对于其他浏览器可以使用 HTML5 下载标签。

【问题讨论】:

    标签: javascript html csv utf-8 character-encoding


    【解决方案1】:

    这里缺少什么,我们需要明确说明什么是分隔符。在写入文档之前应添加以下行

    csvText = 'sep=,\r\n' + csvText;
    

    AndrewB - Convert HTML table to CSV in jQuery , 是列分隔符,\r\n 是行分隔符。此外,如果您使用 c/c++ 编写此代码,我们需要将 \r\n 转义为 \r\n 并根据上下文使用 ' 或 "

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-17
      • 1970-01-01
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      相关资源
      最近更新 更多