getXls <- function( filename, #the name of the excel file sheet=NULL, #the name or the number of the sheet to get area=NULL, #the reading area of the chosen sheet simplify=FALSE #whether to transform the data to matrix or not ){ if( !any(search()=="package:RODBC") ) { lib <- try(library(RODBC), silent=TRUE) if(class(lib)=="try-error") { stop("Please install the package from the CRAN.") } } con <- odbcConnectExcel(filename) shnames <- sqlTables(con)$TABLE_NAME shnames <- substr(shnames, 1, nchar(shnames)-1) names(shnames) <- as.character(seq(along=shnames)) if( nrow(sqlTables(con))==0 ) { stop( paste("There is no available book named <", filename, ">, or it contains 0 sheet.", sep="") ) } if(is.null(sheet)) { cat("There exist ", length(shnames), " sheets in the excel book.\n\n", sep="") print(shnames) input <- readline("Hit the number or the name of the sheet you want to import : ") cat("\n") sheet <- suppressWarnings(as.numeric(input)) if( is.na(sheet) ) { sheet <- input } } if(is.numeric(sheet)) { sheet <- shnames[sheet] } qry <- paste("select*from [", sheet, "$]", sep="") tabread <- sqlQuery(con, qry) odbcClose(con) if(!is.null(area)) { cmpLETTERS <- c(LETTERS, paste(rep(LETTERS, each=26), rep(LETTERS, 26), sep="")) fromto <- strsplit(area, ":")[[1]] tabcols <- substr(fromto, 1, regexpr("[0-9]", fromto)-1) tabcols <- c( which(cmpLETTERS == tabcols[1]), which(cmpLETTERS == tabcols[2]) ) #from "A" to "ZZ" is supported as column indices tabcols <- sort(tabcols) tabrows <- substring(fromto, regexpr("[0-9]", fromto)) tabrows <- as.numeric(tabrows) tabrows <- sort(tabrows) tabread <- tabread[tabrows[1]:tabrows[2], tabcols[1]:tabcols[2]] } if(simplify) { tabread <- as.matrix(tabread) } return(tabread) } comment(getXls) <- c( "getXls - Import MS Excel file using RODBC package.", "", "SYNOPSIS", " xls <- getXls(filename)", "INPUT", " filename : the name of the excel file (=book) you want to import.", " sheet : the sheet number (or the name) you want to get from the excel book.", " You can choose it in the R console if you don't remark this parameter.", " area : character. the reading area designation in excel-like manner.", " e.g. 'A1:C20'", " simplify : logical. whether to transform the imported data as a matrix.", "OUTPUT", " xls : data.frame or matrix object.", "", "See http://www7b.biglobe.ne.jp/~homunculus/r/getXls.html for detailed instruction in Japanese.", "ver.1.02, written by MOCHI, 2009." )