csv 使用BOM将UTF-8数据转换为UTF-16

vmjh9lq9  于 2023-07-31  发布在  其他
关注(0)|答案(1)|浏览(121)

我有一个名为csv的变量,它包含了我需要的所有数据。我想将此数据转换为UTF-16LE,因为我希望Excel只需打开文件即可识别数据,而不需要Get Data按钮。
我尝试使用this solution,虽然LibreOffice Calc确实识别出它是一个UTF-16文件,但Excel无法正确解码希腊字符。
下面是我的JavaScript代码:

csv = csvRows.join('\r\n')

      var byteArray = new Uint8Array(csv.length * 2);
      for (var i = 0; i < csv.length; i++) {
        byteArray[i * 2] = csv.charCodeAt(i) // & 0xff;
        byteArray[i * 2 + 1] = csv.charCodeAt(i) >> 8 // & 0xff;
      }

      var blob = new Blob([byteArray], { type: 'text/csv', encoding: "UTF-16LE" });
      var url = URL.createObjectURL(blob);
      sendFileToClient(url, this.el.id + ".csv")

字符串
我在Elixir中遇到的一个类似问题,我通过使用:unicode模块解决了,如下所示:

csv =
      :unicode.characters_to_binary(
        :unicode.encoding_to_bom(:utf8) <> build_csv(data),
        :utf8,
        {:utf16, :little}
      )


我还尝试在文件的开头添加一个\uFEFF BOM字符,但这使得它被识别为UTF-8 BOM文件(根据Notepad++)。当我尝试\uFFFE时,UTF-BOM字符被转换为不同的字母。 [LibreOffice Calc opening the file without BOM](https://i.stack.imgur.com/0uHEl.png)的 [LibreOffice Calc opening the file with\ufeff` BOM](https://i.stack.imgur.com/Rqo84.png)
Excel opening the file without BOM
Excel opening the file with BOM

mnowg1ta

mnowg1ta1#

我通过在将内容转换为UTF-16之前添加UTF-8 BOM解决了这个问题。

相关问题