简体   繁体   English

Internet Explorer中的execCommand使用USC-2 Little Endian编码保存csv文件,如何以UTF-8格式保存?

[英]execCommand in internet explorer saves the csv file using USC-2 Little endian encoding, how to save it with UTF-8 format?

The execCommand always save the .csv file in USC-2 little indian format, but I want it in UTF-8 format. execCommand始终将.csv文件保存为USC-2小印度格式,但我希望使用UTF-8格式。 Also when I change the file name to .txt, the encoding is properly UTF-8. 另外,当我将文件名更改为.txt时,编码正确为UTF-8。 How can I achevie UTF-8 encoding for csv file? 如何为CSV文件实现UTF-8编码? I did try to set charset to UTF-8 but it did not work. 我确实尝试将字符集设置为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);

The file is generated with proper contents but the encoding is not UTF-8 and hence excel does not recognize columns and entire row is displayed in single column. 该文件是用适当的内容生成的,但是编码不是UTF-8,因此excel无法识别列,并且整行显示在单列中。 Produced file (fileNam.csv): 产生的档案(fileNam.csv):

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

I want to do this using javascript and specifically for IE. 我想使用javascript专门用于IE。 I know that for other browsers the HTML5 download tag can be used. 我知道对于其他浏览器,可以使用HTML5下载标签。

Here is what was missing, we need to explicitly say what is the separator. 这是缺少的内容,我们需要明确地说出分隔符是什么。 The below line should be added before writing to document 在写入文档之前,应添加以下行

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

AndrewB - Convert HTML table to CSV in jQuery , is the column separator and \\r\\n is row separator. AndrewB-在jQuery中将HTML表转换为CSV ,是列分隔符,\\ r \\ n是行分隔符。 Also, if you are writing this using c/c++, we need to escape \\r\\n as \\r\\n and depending on context use ' or " 另外,如果您使用c / c ++编写此代码,则需要将\\ r \\ n转换为\\ r \\ n,并根据上下文使用'或“

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM