简体   繁体   中英

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)

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

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, eg using writexl::write_xlsx you could do:

writexl::write_xlsx(list(sheet1 = mtcars[1:10, ], sheet2 = mtcars[11:20, ]), "mtcars.xlsx")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM