0

I have a excel file data.xlsx, which has two sheets Sheet1 and Sheet2, now I want to append df1 and df2 from R into data.xlsx with names Sheet3 and Sheet4, I have tried with:

library(xlsx)
write.xlsx(df1, "data.xlsx", sheetName = "Sheet3", row.names = FALSE)
write.xlsx(df2, "data.xlsx", sheetName = "Sheet4", row.names = FALSE)

But it overwrites the orginal file's Sheet1 and Sheet2, how could we solve this problem?

Thanks.

xarena
  • 95
  • 8
  • 1
    This might help https://stackoverflow.com/questions/34643888/how-do-i-append-data-from-a-data-frame-in-r-to-an-excel-sheet-that-already-exist – Ronak Shah Jul 22 '20 at 04:06
  • In both occasions - your question and your answer - you didn't provide the name of the package you're using (I suppose it is `openxlsx`). In this way, you are the only person benefited with your question, which is not the intent of stackoverflow. You should edit question and answer to explicitly in a way that both encompass the package information. – rdornas Jul 22 '20 at 14:18
  • I think it should be `library(xlsx)` – xarena Jul 22 '20 at 14:43

2 Answers2

2

The package xlsx allows you to do this.

http://www.sthda.com/english/wiki/r-xlsx-package-a-quick-start-guide-to-manipulate-excel-files-in-r#add-a-table-into-a-worksheet

1

This solution may works:

library(xlsx)
# Write the first dataset df1 in a workbook
write.xlsx(df1, file = 'data.xlsx', sheetName = 'Sheet3, append = TRUE)
# Add a second dataset df2 in a new worksheet
write.xlsx(df2, file = 'data.xlsx', sheetName = 'Sheet4', append = TRUE)
xarena
  • 95
  • 8