简体   繁体   English

如何使用 data.table 的 fwrite 以字符格式保存 Excel 的数字

[英]How to preserve numbers in a character format for Excel with data.table's fwrite

In the example below, when I save the number in a character format (ie, .10) as a CSV file using data.table 's fwrite , Excel displays it as a number rather than a character string.在下面的示例中,当我使用data.tablefwrite将数字以字符格式(即 .10)保存为 CSV 文件时,Excel 将其显示为字符串。

Is there a way to save the number in a character format that Excel can recognize as a string?有没有办法以 Excel 可以识别为字符串的字符格式保存数字?

I'm not simply trying to remove the 0 before the decimal point or keep the trailing 0.不是简单地尝试删除小数点前的 0 或保留尾随的 0。

I'd like to keep the character strings intact , exactly as they would be displayed in R (eg, .10 but without the quotation marks).我想保持字符串完整,就像它们在 R 中显示的一样(例如,.10 但没有引号)。

dt <- data.table(a = ".10")
fwrite(dt, "example.csv")

# The saved CSV file opened in Excel shows the number 0.1, rather than the string .10

Excel is mostly brain-dead with regards to reading things in as you want. Excel 在阅读你想要的东西方面几乎是脑残。 Here's one workaround:这是一种解决方法:

dat <- data.frame(aschr = c("1", "2.0", "3.00"), asnum = 1:3, hascomma = "a,b", hasnewline = "a\nb", hasquote = 'a"b"')
notnumber <- sapply(dat, function(z) is.character(z) & all(is.na(z) | !grepl("[^-0-9.]", z)))
needsquotes <- sapply(dat, function(z) any(grepl('[,\n"]', z))) & !notnumber
dat[needsquotes] <- lapply(dat[needsquotes], function(z) dQuote(gsub('"', '""', z), FALSE))
dat[notnumber] <- lapply(dat[notnumber], function(z) paste0("=", dQuote(z, FALSE)))
fwrite(dat, "iris.csv", quote = FALSE)

Resulting in the following perspective in Excel.导致Excel中的以下透视。

Excel 的 CSV 文件视图的屏幕截图

Most of this is precautionary: if you know your data well and you know that none of the data contains commas, quotes, or newlines, then you can do away with the needsquotes portions.其中大部分是预防性的:如果您非常了解您的数据并且您知道所有数据都不包含逗号、引号或换行符,那么您可以取消需要needsquotes部分。 notnumber is the column(s) of interest. notnumber是感兴趣的列。

Bottom line, we "trick" excel into keeping it a string by forcing it as an excel formula.底线,我们“欺骗” excel 通过将其强制为 excel 公式将其保留为字符串。 This may not work with other spreadsheets (eg, Calc), I haven't tested.这可能不适用于其他电子表格(例如,Calc),我没有测试过。

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

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