Question
If I want to manipulate a worksheet in an EXISTING workbook using R and the openxlsx
package, how do I assign that to a variable for use in script?
Example
It's easy to do this (and well documented) when you are creating a workbook from scratch:
library(openxlsx)
f <- "Excel Output/Example.xlsx"
df <- data.frame("ColA" = c("A", "B", "C"),
"ColB" = c(1L, 4L, 9L))
wb <- createWorkbook()
sh <- addWorksheet(wb, sheetName = "MyExampleSheet")
# Now go do stuff using the `sh` variable like...
writeData(wb, sh, df)
saveWorkbook(wb, file = f, overwrite = TRUE)
But now let's say I'm not creating a workbook from scratch. I'm using an existing workbook with sheets pre-existing, and I want to write new data to those existing sheets:
wb <- loadWorkbook(f) # Loading, not creating!
sh <- addWorksheet(wb, sheetName = "MyExampleSheet")
#> Error in addWorksheet(wb, sheetName = "MyExampleSheet") :
#> A worksheet by the name 'MyExampleSheet' already exists! Sheet names must be unique case-insensitive.
Obviously addWorksheet()
is the wrong function, but I cannot figure out how to get sh
properly assigned to an existing worksheet.