Joris Meys
Joris Meys

Reputation: 108603

Not using colnames when reading .xls files with RODBC

I have another puzzling problem.

I need to read .xls files with RODBC. Basically I need a matrix of all the cells in one sheet, and then use greps and strsplits etc to get the data out. As each sheet contains multiple tables in different order, and some text fields with other options inbetween, I need something that functions like readLines(), but then for excel sheets. I believe RODBC the best way to do that.

The core of my code is following function :

.read.info.default <- function(file,sheet){
    fc <- odbcConnectExcel(file)    # file connection
    tryCatch({
      x <- sqlFetch(fc,
                    sqtable=sheet,
                    as.is=TRUE,
                    colnames=FALSE,
                    rownames=FALSE
           )
      },
      error = function(e) {stop(e)},
      finally=close(fc)
    )

    return(x)
}

Yet, whatever I tried, it always takes the first row of the mentioned sheet as the variable names of the returned data frame. No clue how to get that solved. According to the documentation, colnames=FALSE should prevent that.

I'd like to avoid the xlsReadWrite package. Edit : and the gdata package. Client doesn't have Perl on the system and won't install it.


Edit:

I gave up and went with read.xls() from the xlsReadWrite package. Apart from the name problem, it turned out RODBC can't really read cells with special signs like slashes. A date in the format "dd/mm/yyyy" just gave NA.

Looking at the source code of sqlFetch, sqlQuery and sqlGetResults, I realized the problem is more than likely in the drivers. Somehow the first line of the sheet is seen as some column feature instead of an ordinary cell. So instead of colnames, they're equivalent to DB field names. And that's an option you can't set...

Upvotes: 2

Views: 552

Answers (1)

Dirk is no longer here
Dirk is no longer here

Reputation: 368579

Can you use the Perl-based solution in the gdata instead? That happens to be portable too...

Upvotes: 1

Related Questions