Import excel workbook with multiple sheets

Daniel Rawlings picture Daniel Rawlings · Mar 19, 2018 · Viewed 14.6k times · Source

I am looking to import an excel workbook into R with multiple sheets. However, I can't seem to quite make this work. The code I have been using is the following:

library(XLConnect)
# Read Excel Sheet
excel <- loadWorkbook("C:/Users/rawlingsd/Downloads/17-18 Prem Stats.xlsx")
# get sheet names
sheet_names <- getSheets(excel)
names(sheet_names) <- sheet_names
# put sheets into a list of data frames
sheet_list <- lapply(sheet_names, function(.sheet){readWorksheet(object=excel, .sheet)})
# limit sheet_list to sheets with at least 1 dimension 
# sheet_list2 <- sheet_list[sapply(sheet_list, function(x) dim(x)[1]) > 0]
# code to read in each excel worksheet as individual dataframes
for (i in 1:length(sheet_list)){assign(paste0("2018df", i), as.data.frame(sheet_list[i]))}
# define function to clean data in each data frame (updated based on your data)

If anyone could help me with my code or share a code that works for them, it would be greatly appreciated

Answer

Sahil Shinde picture Sahil Shinde · Mar 19, 2018

Please look into openxlsx package, which allows you to do loads of stuff with excel workbooks. Here is a code script to read all the sheets from a given workbook.

library(openxlsx)
a <- loadWorkbook('~/filename.xlsx')
sheetNames <- sheets(a)
for(i in 1:length(sheetNames))
{
  assign(sheetNames[i],readWorkbook(a,sheet = i))
}

You can verify the data is loaded in R and can view in your workSpace.

Thanks.