bsun
bsun

Reputation: 11

I want to add a new sheet and avoid replacing the existing sheet in excel while using the writexl package in R

I am using writexl package in R to export data frames to excel sheet.

library(writexl)

However when I use the following code the new data frame (resordered2) replaces the existing excel sheet instead of exporting into the new sheet (Sheet2) as specified in the code.

write_xlsx( list (Sheet2 = resordered2), "C:\\Users\\Bharath\\Desktop\\fastqc\\write.xlsx", col_names = TRUE)

The only way I can see around this issue to create all the date frames at once and list them all under the list argument.

I preferably want to work on one data frame after the other. Is there a way to avoid overwriting the existing sheet and adding a new sheet to the excel file using the write_xlsx function?

Upvotes: 1

Views: 4017

Answers (1)

Giulio Mattolin
Giulio Mattolin

Reputation: 650

If you want to add another sheet to an existing .xlsx file you can do it by using the function write.xlsx of the library xlsx. Specifying the name of the new sheet in the parameter sheetName and setting the parameter append=TRUE.

For example:

library(xlsx)
write.xlsx(data, file="filename.xlsx", sheetName="newsheet", append=TRUE)

Update: since you have problems with xlsx, you can try to use the library openxlsx like this

library(openxlsx)

wb <- createWorkbook()

addWorksheet(wb, sheetName = "newsheet_1")
writeData(wb, sheet = "newsheet", data_1)

addWorksheet(wb, sheetName = "newsheet_2")
writeData(wb, sheet = "newsheet_2", data_2)

saveWorkbook(wb, "filename.xlsx")

Upvotes: 0

Related Questions