The following function writes a list of dataframes to an .xlsx file.
It has two modes, given by argument beside.
- beside = TRUEis the default. It writes just one sheet, with the dataframe name on the first row, then an empty cell, then the dataframe. And repeats this for all dataframes, written side by side.
- beside = FALSEwrites one dataframe per sheet. The sheets' names are the dataframes names. If the list members do not have a name, the name is given by argument- sheetNamePrefix.
The .xlsx file is written in the directory given by argument file.
writeList_xlsx <- function(x, file, beside = TRUE, sheetNamePrefix = "Sheet"){
  xnames <- names(x)
  shNames <- paste0(sheetNamePrefix, seq_along(x))
  if(is.null(xnames)) xnames <- shNames
  if(any(xnames == "")){
    xnames[xnames == ""] <- shNames[xnames == ""]
  }
  wb <- createWorkbook(type = "xlsx")
  if(beside){
    sheet <- createSheet(wb, sheetName = shNames[1])
    row <- createRow(sheet, rowIndex = 1)
    col <- 0
    for(i in seq_along(x)){
      col <- col + 1
      cell <- createCell(row, colIndex = col)
      setCellValue(cell[[1, 1]], xnames[i])
      col <- col + 2
      addDataFrame(x[[i]], sheet, 
                   startRow = 1, startColumn = col,
                   row.names = FALSE)
      col <- col + ncol(x[[i]])
    }
  }else{
    for(i in seq_along(x)){
      sheet <- createSheet(wb, sheetName = xnames[i])
      addDataFrame(x[[i]], sheet, row.names = FALSE)
    }
  }
  if(!grepl("\\.xls", file)) file <- paste0(file, ".xlsx")
  saveWorkbook(wb, file = file)
}
writeList_xlsx(tbl, file = "test.xlsx")
writeList_xlsx(tbl, file = "test2.xlsx", beside = FALSE)