-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.

zx8754
  • 52,746
  • 12
  • 114
  • 209

2 Answers2

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')
Kent Johnson
  • 3,320
  • 1
  • 22
  • 23
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...

dario
  • 6,415
  • 2
  • 12
  • 26