-1

My loop is completely doing what I want it to do apart from when writing out the data I want it to loop through and open a new sheet each time, it is not doing this but simply overwriting the data in the single excel file. My code is:

file2 <- paste("filelocation", sep = "")
write.xlsx(Combined, file2, sheetName = (i))

I do not know why this isn't working as this exact same code is working for me earlier in the code.

0

2 Answers 2

2

Here is a simple example that writes a workbook with three identical sheets. Change the sheet contents to suit...

library(openxlsx)

wb = createWorkbook()
for (i in 1:3) {
  sheet_name = paste('mtcars', i)
  addWorksheet(wb, sheet_name)
  writeData(wb, sheet_name, mtcars)
}

saveWorkbook(wb, 'my_workbook.xlsx')
Sign up to request clarification or add additional context in comments.

Comments

1
write.xlsx(Combined, file2, sheetName = (i), append=TRUE)

From xlsx documentation:

append a logical value indicating if x should be appended to an existing file. If TRUE the file is read from disk.

Edit:

This does not work – Natasha Jones

This code works for me as intended:

library(xlsx)
write.xlsx(mtcars, "test.xlsx", sheetName ="firstSheet")
write.xlsx(mtcars, "test.xlsx", sheetName ="secondSheet", append=TRUE)
write.xlsx(mtcars, "test.xlsx", sheetName ="thirdSheet", append=TRUE)

The resulting .xlsx file has 3 sheets! You have to pass a character string to the argument sheet

sheetName a character string with the sheet name. I.e.

for (i in 1:4) {
  write.xlsx(mtcars, "test.xlsx", sheetName = as.character(i), append=TRUE)
}

This works for me also...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.