简体   繁体   中英

How do I access an **EXISTING** sheet in a workbook using `openxlsx` in R?

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.

In your example you don't need sh . Worksheets are accessed via sheet name only.

library(openxlsx)

# creating data
df <- data.frame("ColA" = c("A", "B", "C"),
                 "ColB" = c(1L, 4L, 9L))

# create workbook from scratch
wb <- createWorkbook()
addWorksheet(wb, sheetName = "MyExampleSheet")
writeData(wb, "MyExampleSheet", df)

# loading workbook and writing onto it
f <- system.file("extdata", "loadExample.xlsx", package = "openxlsx")

wb <- loadWorkbook(file = f)
writeData(wb, "testing", df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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