How to extract sheet names from Excel file in R
Asked Answered
V

5

41

I have loaded a workbook into R and read in the worksheets using xlConnect, but I was wondering if there was a way of extracting the names of the sheets perhaps in a vector?

So far my code is:

dataIn<-loadWorkbook(file.path(filenames[1],sep=""))
lst = readWorksheet(dataIn, sheet = getSheets(dataIn), startRow=1, startCol=1, header=TRUE)

...and I want to extract the sheet names of the sheets in lst.

Vitiate answered 30/7, 2013 at 10:39 Comment(1)
names(getSheets(dataIn)) will give you list of names of sheetsHendricks
R
27

You are looking for getSheets

Returns all worksheet names in a workbook.
Rodmann answered 30/7, 2013 at 10:50 Comment(0)
B
78

Another really nice package developed by the folks at RStudio is readxl. It's easy to get the excel sheet names with the excel_sheets() function.

library(readxl)
path <- "path/to/your/file.xlsx"
excel_sheets(path = path)
Beatup answered 1/7, 2017 at 10:45 Comment(1)
imo this should be the no.1 answer these daysVerne
R
27

You are looking for getSheets

Returns all worksheet names in a workbook.
Rodmann answered 30/7, 2013 at 10:50 Comment(0)
C
9

In the "openxlsx" package it would be a command "getSheetNames":

library(openxlsx)
path <- "path/to/your/file.xlsx"
getSheetNames(path)
Consumer answered 27/12, 2019 at 15:26 Comment(0)
A
0

Here is another approach that can be considered :

library(RDCOMClient)
xlApp <- COMCreate("Excel.Application")
xlApp[["DisplayAlerts"]] <- FALSE
xlApp[["Visible"]] <- TRUE

path_To_Excel_File <- "D:/excel_File.xlsx"
xlWbk <- xlApp$Workbooks()$Open(path_To_Excel_File)
nb_Sheets <- xlWbk$Sheets()$Count()
sheets_Names <- character(nb_Sheets)

for(i in 1 : nb_Sheets)
{
  sheets_Names[i] <- xlWbk$Sheets(i)$Name()
}
Ambience answered 20/5, 2023 at 23:44 Comment(0)
A
0

Easiest way to do this after using loadWorkbook, using code from the user's example:

dataIn<-loadWorkbook(file.path(filenames[1],sep=""))
names(dataIn)

This will print out all the sheets your current workbook object has.

Arcuate answered 20/2 at 7:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.