rexcelfile-io

Write a list in r to an excel file


I have a list containing 5 dataframes of different length. I want to write those dataframes in the same excel sheet.

I have already tried using WriteXLS() and write.xlsx() but could not get the desired result.


Solution

  • Here's an example where xlsx package functions are used to write 5 different tables on the same sheet :

    library(xlsx)
    
    ### create a sample list
    set.seed(123)
    theList <- list()
    
    theList$df1 <- data.frame(a=1:5,b=sample(c('X','Y','Z'),5,T))
    theList$df2 <- data.frame(a=1:3,b=sample(c('X','Y','Z'),3,T),c=sample(c('A','B','C'),3,T))
    theList$df3 <- data.frame(answer=42)
    theList$df4 <- data.frame(x=1:2,y=sample(c('I','J','K'),2,T),z='M')
    theList$df5 <- data.frame(m=1.2345,n='foo')
    ###
    
    
    wb <- createWorkbook()
    sheet <- createSheet(wb,"SheetNameHere")
    
    currRow <- 1
    for(i in 1:length(theList)){
    
      cs <- CellStyle(wb) + Font(wb, isBold=TRUE) + Border(position=c("BOTTOM", "LEFT", "TOP", "RIGHT"))
    
      addDataFrame(theList[[i]],
                   sheet=sheet,
                   startRow=currRow,
                   row.names=FALSE,
                   colnamesStyle=cs)
    
      currRow <- currRow + nrow(theList[[i]]) + 2 
    }
    
    saveWorkbook(wb,file = "myXlsx.xlsx")
    

    Result:

    Excel Snapshot