Writing multiple data into one Excel worksheet using xlsx and R

I have a set of csv files in different directories, I would like to put them all in one excel file, each table in one excel sheet.

I use R and xlsx.

# loading the library
library(xlsx)
rm(list = ls())

# getting the path of all reports (they are in csv format)
restab = system("ls /home/ubuntu/ibasruns/control/*/report",intern = TRUE)

# creating work book
wb <- createWorkbook()


# going through each csv file
for (item in restab)
{
    # making each as a sheet
    sheet <- createSheet(wb, sheetName=strsplit(item,"/")[[1]][6])
    addDataFrame(read.csv(item), sheet)
    # saving the workbook
    saveWorkbook(wb, "AliceResultSummary.xlsx")
}

# finally writing it.
write.xlsx(wb, "AliceResultSummary.xlsx")

However, in the last line, I get the following error:

Error in as.data.frame.default (x [[i]], optional = TRUE): cannot coerce class "(" jobjRef ", package =" rJava ")" in data.frame

Is there something I am missing?

+4
source share
1 answer

You are close:

# creating work book
wb <- createWorkbook()


# going through each csv file
for (item in restab)
{
    # create a sheet in the workbook
    sheet <- createSheet(wb, sheetName=strsplit(item,"/")[[1]][6])

    # add the data to the new sheet
    addDataFrame(read.csv(item), sheet)
}

# saving the workbook
saveWorkbook(wb, "AliceResultSummary.xlsx")

write.xlsxnot required here; it was just used to create a book from a single data frame.

+8
source

All Articles