使用openxlsx将数据框导出为r中的excel工作表,并将数字单元格识别为数字(摆脱格式为文本错误的数字)

rfbsl7qr  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(182)

是否有办法确保使用openxlsx将数字导出为数字?
使用下面的例子,带数字的单元格被导出为文本。2我相信部分原因是列同时包含文本和数字(即作为字符列读取)。3如果我将其更改为数字,将导致数据丢失。
有什么建议吗?我试着通读软件包文档,但找不到可以完成此功能的特定参数。

dff = data.frame(var1 = c("a", "b", "c", "1"), var2=c("1", "c", 2, "1/1/2020"))

wb22= createWorkbook()
addWorksheet(wb22, "sheet1")
writeData(wb22, sheet="sheet1", x=dff, startRow = 1,
          startCol = 1, colNames = TRUE)
saveWorkbook(
  wb22,
  file = "example22.xlsx",
  overwrite = TRUE
)

browseURL("example22.xlsx")
t98cgbkg

t98cgbkg1#

根据stefan的评论,dataframe列只能有一种数据类型。
解决方法可能是在Excel中添加一个虚拟公式,将数字(存储为字符)转换回数字,然后保持其他内容不变。
例如:

dff = data.frame(var1 = c("a", "b", "c", "1"), var2=c("1", "c", 2, "1/1/2020"))

wb22= createWorkbook()
addWorksheet(wb22, "sheet1")
writeData(wb22, sheet="sheet1", x=dff, startRow = 1,
          startCol = 1, colNames = TRUE)

## New column will be added with header called var2_new
writeData(wb22, sheet="sheet1", x= "var2_new", startRow = 1, startCol = 3)

## Excel formula to convert numbers back to numbers and everything else as is. 
## by multiplying by 1. If there is an error use the column value as is.
xl_formula <- paste0('IFERROR(B', 2:(nrow(dff) + 1), '*1, B', 2:(nrow(dff) + 1), ')')
writeFormula(wb22, sheet = "sheet1", xl_formula, startRow = 2,startCol = 3) 

saveWorkbook(
  wb22,
  file = "example22_new.xlsx",
  overwrite = TRUE
)

相关问题