I'm developing a part of an application that's responsible for exporting some data into CSV files. The application always uses UTF-8 because of its multilingual nature at all levels. But opening such CSV files (containing e.g. diacritics, cyrillic letters, Greek letters) in Excel does not achieve the expected results showing something like Г„/Г¤, Г–/Г¶. And I don't know how to force Excel understand that the open CSV file is encoded in UTF-8. I also tried specifying UTF-8 BOM EF BB BF, but Excel ignores that.

有什么解决办法吗?

附注:哪些工具可能像Excel一样?


更新

I have to say that I've confused the community with the formulation of the question. When I was asking this question, I asked for a way of opening a UTF-8 CSV file in Excel without any problems for a user, in a fluent and transparent way. However, I used a wrong formulation asking for doing it automatically. That is very confusing and it clashes with VBA macro automation. There are two answers for this questions that I appreciate the most: the very first answer by Alex https://stackoverflow.com/a/6002338/166589, and I've accepted this answer; and the second one by Mark https://stackoverflow.com/a/6488070/166589 that have appeared a little later. From the usability point of view, Excel seemed to have lack of a good user-friendly UTF-8 CSV support, so I consider both answers are correct, and I have accepted Alex's answer first because it really stated that Excel was not able to do that transparently. That is what I confused with automatically here. Mark's answer promotes a more complicated way for more advanced users to achieve the expected result. Both answers are great, but Alex's one fits my not clearly specified question a little better.


更新2

在最后一次编辑5个月后,我注意到Alex的答案不知为何消失了。我真的希望这不是一个技术问题,我希望现在不再有关于哪个答案更好的讨论。所以我认为马克的答案是最好的。


当前回答

是的,这是可能的。当写入流创建csv时,要做的第一件事是:

myStream.Write(Encoding.UTF8.GetPreamble(), 0, Encoding.UTF8.GetPreamble().Length)

其他回答

我们使用了以下方法:

转换CSV到UTF-16 LE 在文件开头插入BOM 使用制表符作为字段分隔符

现在是2022年3月,似乎我们不能同时使用BOM和sep=…线。 添加sep=\t或类似的,使Excel忽略BOM。

使用分号似乎是Excel的默认理解,在这种情况下,我们可以跳过sep=…这样就行了。

这是微软365与Excel版本2110构建14527.20276。

php生成的CSV文件也有同样的问题。 当分隔符在内容开头通过“sep=,\n”定义时(当然是在BOM之后),Excel会忽略BOM。

因此,在内容的开头添加一个BOM ("\xEF\xBB\xBF"),并通过fputcsv($fh, $data_array, ";")设置分号作为分隔符;很管用。

下载并安装LibreOffice Calc 在LibreOffice Calc中打开您选择的csv文件 谢天谢地,一个导入文本向导出现了…… ...选择分隔符和字符编码选项 在Calc中选择结果数据并复制粘贴到Excel中

简单的vba宏用于打开utf-8文本和csv文件

Sub OpenTextFile()

   filetoopen = Application.GetOpenFilename("Text Files (*.txt;*.csv), *.txt;*.csv")
   If filetoopen = Null Or filetoopen = Empty Then Exit Sub

   Workbooks.OpenText Filename:=filetoopen, _
   Origin:=65001, DataType:=xlDelimited, Comma:=True

End Sub

原点:=65001为UTF-8。 逗号:对于按列分布的.csv文件为True

保存在个人。XLSB使它始终可用。 个性化excel工具栏添加一个宏调用按钮,并从那里打开文件。 您可以添加更多的格式到宏,如列自动拟合,对齐等。