Sunday, November 28, 2010

Export to multiple-sheet xls file in R

It's easy to export a data frame or table to .csv file in R. However, sometimes one want to save to a .xls file directly. You can certainly first export to a .csv file and convert it to a .xls file in Microsoft Excel, but the following R codes can do this job directly with ability to save a multiple-sheet .xls file.

> install.packages("RODBC")
> library(RODBC)
> save2excel <- function(x, tname) sqlSave(xlsFile, x, tablename = tname, rownames = FALSE, addPK = T)
> xlsFile <- odbcConnectExcel("C:\\Temp\\test.xls", readOnly = FALSE)
> temp1 <- data.frame(x = rnorm(100), y = rnorm(100))
> temp2 <- data.frame(x = rnorm(100), y = rnorm(100))
> save2excel(temp1, "test1") # Here test is the name of current sheet
> save2excel(temp2, "test2")
> odbcCloseAll()

No comments:

Post a Comment