13

Is it possible to generate a list of sheetnames within an xlsx file? Or perhaps, can I check if a sheet name exists, and if not, proceed with some designated function?

user1664455
  • 131
  • 1
  • 1
  • 3

7 Answers7

17

With xlsx library you can get the list of the sheets in an existing workbook with getSheets():

wb <- loadWorkbook(your_xlsx_file)
sheets <- getSheets(wb) 
Geza
  • 464
  • 6
  • 16
7

Yes, I have done that with the xlsx package which (just like the XLConnect package) uses a Java backend with the Apache POI code -- so it is cross-platform.

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
3

None of the above solutions worked for a big xlsx of more than 300 sheets.

Only this worked in my case:

library(openxlsx)
sheetNames <- getSheetNames("filename.xlsx")
stallingOne
  • 3,633
  • 3
  • 41
  • 63
2

You can also do this with the RODBC package:

h <- odbcConnectExcel2007("file.xlsx")
sqlTables(h)
Hong Ooi
  • 56,353
  • 13
  • 134
  • 187
0

To get excel or workbook file sheet names using R xlsx package, load your workbook or excel file, in my case e.g. name of excel file is "input_4_r.xlsx"

> wb<-loadWorkbook("input_4_r.xlsx")

See the list of files, here it shows 2 sheets in my example case in my example, I have not named first sheet and kept the default but 2nd sheet, I named as "name city" and hence the output below.

> getSheets(wb)
$Sheet1
[1] "Java-Object{Name: /xl/worksheets/sheet1.xml - Content Type: application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml}"

$`name city`
[1] "Java-Object{Name: /xl/worksheets/sheet2.xml - Content Type: application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml}"

You can see the names of sheetnames as below.

> names(getSheets(wb))
[1] "Sheet1"    "name city"

To get the name of specific index of sheet, e.g. passing [2] in my case for 2nd sheet.

> names(getSheets(wb))[2]
[1] "name city"

Assumption for above is xlsx package is installed and loaded in R

jay.sf
  • 60,139
  • 8
  • 53
  • 110
0

A oneline solution using openxlsx would be

openxlsx::getSheetNames('your/file.xlsx')
loki
  • 9,816
  • 7
  • 56
  • 82
0

The following approach could also be considered with the RDOMClient R package :

library(RDCOMClient)
xlApp <- COMCreate("Excel.Application")
path_To_Excel_File <- "D:/my_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()
}
Emmanuel Hamel
  • 1,769
  • 7
  • 19