Easy way to export multiple data.frame to multiple Excel worksheets Easy way to export multiple data.frame to multiple Excel worksheets r r

Easy way to export multiple data.frame to multiple Excel worksheets


You can write to multiple sheets with the xlsx package. You just need to use a different sheetName for each data frame and you need to add append=TRUE:

library(xlsx)write.xlsx(dataframe1, file="filename.xlsx", sheetName="sheet1", row.names=FALSE)write.xlsx(dataframe2, file="filename.xlsx", sheetName="sheet2", append=TRUE, row.names=FALSE)

Another option, one that gives you more control over formatting and where the data frame is placed, is to do everything within R/xlsx code and then save the workbook at the end. For example:

wb = createWorkbook()sheet = createSheet(wb, "Sheet 1")addDataFrame(dataframe1, sheet=sheet, startColumn=1, row.names=FALSE)addDataFrame(dataframe2, sheet=sheet, startColumn=10, row.names=FALSE)sheet = createSheet(wb, "Sheet 2")addDataFrame(dataframe3, sheet=sheet, startColumn=1, row.names=FALSE)saveWorkbook(wb, "My_File.xlsx")

In case you might find it useful, here are some interesting helper functions that make it easier to add formatting, metadata, and other features to spreadsheets using xlsx:http://www.sthda.com/english/wiki/r2excel-read-write-and-format-easily-excel-files-using-r-software


You can also use the openxlsx library to export multiple datasets to multiple sheets in a single workbook.The advantage of openxlsx over xlsx is that openxlsx removes the dependencies on java libraries.

Write a list of data.frames to individual worksheets using list names as worksheet names.

require(openxlsx)list_of_datasets <- list("Name of DataSheet1" = dataframe1, "Name of Datasheet2" = dataframe2)write.xlsx(list_of_datasets, file = "writeXLSX2.xlsx")


There's a new library in town, from rOpenSci: writexl

Portable, light-weight data frame to xlsx exporter based on libxlsxwriter. No Java or Excel required

I found it better and faster than the above suggestions (working with the dev version):

library(writexl)sheets <- list("sheet1Name" = sheet1, "sheet2Name" = sheet2) #assume sheet1 and sheet2 are data frameswrite_xlsx(sheets, "path/to/location")