79785732

Date: 2025-10-08 17:46:33
Score: 1.5
Natty:
Report link

The following approach will keep the format of existing worksheets.

# Create an existing workbook from which we want to extract sheets
firstWb <- createWorkbook()
addWorksheet(firstWb, sheetName = "One")
addWorksheet(firstWb, sheetName = "Two")
addWorksheet(firstWb, sheetName = "Three")
writeData(firstWb, sheet = "One", x = matrix(1))
writeData(firstWb, sheet = "Two", x = matrix(2))
writeData(firstWb, sheet = "Three", x = matrix(3))

# Make a copy and remove sheets that we dont want to merge
theWb <- copyWorkbook(firstWb)
openxlsx::removeWorksheet(theWb, "One")

# Add new sheets
addWorksheet(theWb, sheetName = "Zero")
writeData(theWb, sheet = "Zero", x = matrix(0))
addWorksheet(theWb, sheetName = "Five")
writeData(theWb, sheet = "Five", x = matrix(5))

# Reorder sheets
nams <- 1:length(names(theWb))
names(nams) <- names(theWb)
worksheetOrder(theWb) <- nams[c("Zero", "Two", "Three", "Five")]

# Save
saveWorkbook(theWb, file = "Combined.xlsx")

If anyone found this answer helpful, please consider showing your appreciation with an upvote.

Reasons:
  • Blacklisted phrase (2): anyone found
  • Blacklisted phrase (0.5): upvote
  • Long answer (-1):
  • Has code block (-0.5):
  • Low reputation (0.5):
Posted by: Daniel Hoop