0

I am currently using write_excel_csv2 from readxl to write a data.frame in R to an excel file. How can I write two data.frames to two worksheets within the same excel file? To give an example, how can I combine the following two files to one?

write_excel_csv2(mtcars[1:10,], file_name1)
write_excel_csv2(mtcars[11:20,], file_name2)
Claudio Moneo
  • 489
  • 1
  • 4
  • 10

2 Answers2

2

You can write each DF to the same xlsx.file and specify different names for the worksheets. You have to use append = TRUE for the second worksheet.

library(xlsx)
write.xlsx(mtcars[1:10,], file="filename.xlsx", sheetName="sheet1", row.names=FALSE)
write.xlsx(mtcars[11:20,], file="filename.xlsx", sheetName="sheet2", append=TRUE, row.names=FALSE)

This solution comes from here

MarBlo
  • 4,195
  • 1
  • 13
  • 27
1

write_excel_csv2 just exports your data as a csv. If you want to export to excel have a look at writexl or openxlsx or ... packages, e.g. using writexl::write_xlsx you could do:

writexl::write_xlsx(list(sheet1 = mtcars[1:10, ], sheet2 = mtcars[11:20, ]), "mtcars.xlsx")
stefan
  • 90,330
  • 6
  • 25
  • 51