Extract the number of sheets from an Excel workbook in R (without XLConnect)
Asked Answered
H

2

13

I'm relatively new to R (and programming). I have an Excel workbook with 36 sheets, but suppose that I don't know how many sheets there are and I want my code to find that out for me. I have tried something like:

options(java.parameters = "-Xmx6g")
library(XLConnect)
myWorkbook <- loadWorkbook(filename)
numberofsheets <- length(getSheets(myWorkbook))

But even though I set my memory to 6GB I still run into memory errors with XLConnect, so I would like to use other packages (e.g. xlsx, openxlsx). Is there a way to find out the number of sheets in an Excel workbook without using XLConnect? Thanks for your help.

Houstonhoustonia answered 11/11, 2016 at 11:35 Comment(2)
@rosscova's solution is useful because you don't have to load the file to get count. With XLConnect you could do wbObj=xlsx::loadWorkbook("test.xlsx");numSheets = wbObj$getNumberOfSheets()Lacrimatory
just to round out with library(xlsx). Almost identical syntax to your current: wb <- loadWorkbook(file); names(getSheets(wb) I skip the Java object list and just use names for indexing and passing into read.xlsx(sheetName = sheet).Counterproof
M
29

Maybe try:

library( readxl )
length( excel_sheets( filename ) )
Monophony answered 11/11, 2016 at 11:52 Comment(0)
M
3

This should do exactly what you want.

gdata::sheetCount("your_path_here.xlsx")

Also, to list the sheet names as an array.

library(purrr)
library(readxl)

file <- 'your_path_here.xlsx'

sheets <- excel_sheets(file)
Misogamy answered 15/11, 2016 at 22:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.