简体   繁体   English

将特殊字符从 R 导出到 excel/csv

[英]Exporting special characters from R to excel/csv

I have a vector in R that contains special characters, eg x = "Köln" .我在 R 中有一个包含特殊字符的向量,例如x = "Köln"

I have trouble exporting that back to either excel or csv format (preferably in Excel).我无法将其导出回 excel 或 csv 格式(最好在 Excel 中)。

Here is what I tried:这是我尝试过的:

`#Exporting to excel
library(excel.link)
myExcelProcess = COMCreate("Excel.Application")
xl.workbook.add()
excelRange = myExcelProcess[["ActiveSheet"]]$Range("A1:A1")
xl.write(x, excelRange, row.names = FALSE) # this creates an excel file with "ruined" characters (Köln)`

#Exporting to csv write.csv(x = routesCities, file = "out.csv", fileEncoding = "UTF-8") # This creates a csv containing "Koln" - the Umlaut has disappeared.

Any help would be greatly appreciated.任何帮助将不胜感激。

EDIT (Regarding the flagging as possible duplicate): imho the question is rather different than the proposed duplicate, since it refers to encoding issues during data transfer between R and Excel, not failing to run a write.xlsx() function.编辑(关于标记为可能的重复):恕我直言,这个问题与建议的重复有很大不同,因为它指的是 R 和 Excel 之间数据传输期间的编码问题,而不是无法运行write.xlsx()函数。 Furthermore, my attempts do not result in an error (there is no error message), but the results are not the desired ones.此外,我的尝试不会导致错误(没有错误消息),但结果不是预期的。 It might be the case that the same answer (using a different library) could apply here, too, but the question itself is quite different.相同的答案(使用不同的库)也可能适用于这里,但问题本身却大不相同。

The readr package that is part of the tidyverse has a function write_excel_csv that exports data frames to csv in UTF-8 encoding in such a way that opening them directly in excel preserves special characters.作为readr一部分的readr包有一个函数write_excel_csv ,它以 UTF-8 编码将数据帧导出到 csv,这样直接在 excel 中打开它们就可以保留特殊字符。 While I haven't tried exhaustively, I had a similar issue with exporting data with the "greater than or equal to" symbol ≥, represented in string variables as the string \≥.虽然我没有进行过详尽的尝试,但我在导出带有“大于或等于”符号 ≥ 的数据时遇到了类似的问题,在字符串变量中表示为字符串 \≥。 It came out perfectly using this function, even when my previous attempts at using write.csv , even with the option "fileEncoding="UTF-8", had still left strange symbols in the file when opened in excel.它完美地使用了这个函数,即使我之前尝试使用write.csv ,即使使用选项“fileEncoding =“UTF-8”,在excel中打开时仍然在文件中留下奇怪的符号。

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

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