Search code examples
rexport-to-csvexport-to-excel

Writing R dataframes to excel files with multiple worksheets


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)

Solution

  • 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