Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Openxlsx package - Writing multiple tables in one sheet?

Tags:

r

excel

Is it possible to write multiple tables in one excel sheet? From what I have tried, I am seeing that only the last object is being written to the file. It could be that I am overwriting the file each time. So I am wondering how I can modify the code to write both tables in the same sheet? Thanks

data.sets <- ls("package:datasets")[c(5,7)]# list of data set names
foonames <- paste0("foo", seq_along(data.sets))
count <- length(data.sets)  
my.list <- list() 
for (i in 1:count) my.list[[foonames[i]]] <- get(data.sets[[i]])
lapply(my.list, dim)

filen<-sprintf('H:\\11_Analysis\\01_Eye Study\\Output\\Eyestudy1_%s.xlsx',
               Sys.Date());

library(openxlsx)
options("openxlsx.dateFormat" = "yyyy-mm-dd")

wb<-write.xlsx(my.list$foo1, filen, 
               startCol =2, startRow = 1, 
               asTable = T, withFilter = T, 
               colWidths="auto")

wb<-write.xlsx(my.list$foo1, filen, 
               startCol =2, startRow = 15, 
               asTable = T, withFilter = T, 
               colWidths="auto")
like image 941
JeanVuda Avatar asked Oct 30 '17 21:10

JeanVuda


People also ask

How to write multiple tables to the same sheet?

Thanks when you want to write multiple tables to the same sheet, you should create the workbook and then write the data to it and then save it. The way you are doing it seems to be overwriting the data.

Can I save multiple tables in a single Excel file?

The possibility of saving several tables in a single file is a nice feature of Excel. When sharing results with colleagues, it might be useful to compact everything in a single file. As a bioinformatician, I am too lazy to do that manually, and I searched the web for tools that allow doing that.

What is xlsx in R?

This R package simplifies the creation of .xlsx files by providing a high level interface to writing, styling and editing worksheets. Through the use of Rcpp, read/write times are comparable to the xlsx and XLConnect packages with the added benefit of removing the dependency on Java.


1 Answers

when you want to write multiple tables to the same sheet, you should create the workbook and then write the data to it and then save it. The way you are doing it seems to be overwriting the data. Here is what I would do:

wb <- createWorkbook()
addWorksheet(wb, sheetName = "sheet1")

writeData(wb, sheet = 1, x = df, startCol = 2, startRow = 2)
writeData(wb, sheet = 1, x = df2, startCol = 2, startRow = 24)

saveWorkbook(wb, file = "path/to/file.xslx")
like image 129
tbradley Avatar answered Oct 16 '22 10:10

tbradley