# Install and load the openxlsx package
install.packages("openxlsx")
library(openxlsx)
# Create a list of data frames to write to separate sheets
sheets <- list(
df1 = data.frame(a = 1:5, b = letters[1:5]),
df2 = data.frame(c = 6:10, d = LETTERS[6:10])
)
# Create a new workbook
wb <- createWorkbook()
# Add sheets to the workbook
addWorksheet(wb, "Sheet1")
addWorksheet(wb, "Sheet2")
# Write data frames to sheets
writeData(wb, sheet = "Sheet1", sheets$df1)
writeData(wb, sheet = "Sheet2", sheets$df2)
# Save the workbook to an Excel file
saveWorkbook(wb, "multiple_sheets.xlsx", overwrite = TRUE)
Next, we create a new workbook (wb) using the createWorkbook() function, and add sheets to it using the addWorksheet() function. We specify the names of the sheets as strings.
We then write the data frames to the sheets using the writeData() function, passing in the workbook object, the sheet name, and the data frame to write.
Finally, we save the workbook to an Excel file using the saveWorkbook() function, specifying the workbook object and the file name. The overwrite = TRUE argument will overwrite any existing file with the same name.