R语言 openxlsx:仅将工作簿加载/保存为字符

jhdbpxl9  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(185)

我需要在现有的Excel工作簿上进行一些格式设置(其他内容保持不变)。我目前的方法是:

library(openxlsx)

# Open file
wb <- loadWorkbook("C:/myfile.xlsx")

# Formatting
mystyle <- createStyle(border = "Left" )
addStyle(wb, sheet = "Sheet1", style = mystyle, row = 1, cols = 2, gridExpand = T)

# Save
saveWorkbook(wb, "C:/myresult.xlsx", overwrite = T)

**问题:**原始工作簿中的某些单元格(即空白单元格)被解释为数字,因此在保存的文件中显示为NA(而不是空白单元格)。

虽然openxlsx::write.xlsx()允许处理NA(即keepNA),但saveWorkbookloadWorkbook不提供此选项。我不希望使用openxlsx::write.xlsx()等编写单张。

**问题:**如何将整个工作簿声明为“字符”或避免在保存的Excel文件中显示NA(而不是空白单元格)?

hfsqlsce

hfsqlsce1#

我试图重现你的问题,但saveWorkbook显示空白单元格时,NA是你想要的。你尝试更新openxlsx

library(openxlsx)

wb <- createWorkbook()
addWorksheet(wb, "test")
writeData(wb, "test", c(1, NA, 2), startCol = 1, startRow = 1)

mystyle <- createStyle(border = "Left")
addStyle(wb, sheet = "test", style = mystyle,
         row = 1, cols = 2, gridExpand = T)
  
saveWorkbook(wb, "C:/Users/pc36957/Documents/myresult.xlsx", overwrite = T)

**编辑:**问题不是来自openxlsx版本。另一种方法似乎是使用readWorkbook临时从工作表中提取值,然后使用writeDatakeepNA = F参数重写它们。

# Open file
wb <- loadWorkbook("C:/myfile.xlsx")

# temporarily extract sheet as df
temp <- readWorkbook(wb, sheet = "Sheet1", skipEmptyRows = F)

# rewrite data to same sheet
writeData(wb, "Sheet1", temp, keepNA = F, startCol = 1, startRow = 1)

# Formatting
mystyle <- createStyle(border = "Left" )
addStyle(wb, sheet = "Sheet1", style = mystyle, row = 1, cols = 2, gridExpand = T)

# Save saveWorkbook
(wb, "C:/myresult.xlsx", overwrite = T)

相关问题