[R] Yet another question about importing Excel *.xls files

Jerry Floren jerry.floren at state.mn.us
Thu Jan 21 15:56:39 CET 2010


Thanks Gabor, David, and David for all of your help. I did get it to work
with this code that I modified from the R Wiki from Gabor's original
suggestion:


#### START OF CODE ################

library(RODBC) 

### "setwd" Set the working directory ###
setwd("C:/Documents and Settings/jfloren/My Documents/Test_R") 

### Some examples of the Excel file names in this directory ####
# C:/Documents and Settings/jfloren/My Documents/Test_R/MAP_2009 Round 2
2002 Soiltest 9-21-09 .xls
# C:/Documents and Settings/jfloren/My Documents/Test_R/MAP_2009 Round 2
2006 Best Test 10-2-09.xls
# C:/Documents and Settings/jfloren/My Documents/Test_R/MAP_2009 Round 2
4006 A&L Western 10-1-09.xls

## "list.files" List all the file names in this directory that are Excel
files (*.xls extension) ####
fname <- list.files(pattern=".\\.xls", full.names = FALSE, recursive = TRUE,
ignore.case = TRUE) 

#### Count the number of Excel files in this directory ####
z <- length(fname) 

### Print the number of Excel files in this folder ###
print(z) 

for (sp in 1:z) { 

channel <- odbcDriverConnect(paste("DRIVER=Microsoft Excel Driver (*.xls,
*.xlsx, *.xlsm, *.xlsb); DBQ= C:/Documents and Settings/jfloren/My
Documents/Test_R\\",fname[sp],"; ReadOnly=False",sep='')) 
  
sqlTables(channel) 

alldata <- sqlFetch(channel, "Paste Special") 

print(alldata) 
gdata = data.frame(alldata)

write.table(gdata, file = "C:/Documents and Settings/jfloren/My
Documents/Test_R/Test_Import_xls.txt", append = TRUE, quote = TRUE, sep =
"\t", eol = "\n", na = "NA", dec = ".", row.names = FALSE, col.names = TRUE,
qmethod = c("escape", "double"))

odbcClose(channel) 
}

#### END OF CODE #############

I can't tell you how glad I am to get this working. It will save me tons of
drudge work.

Thanks,

Jerry Floren
Minnesota Department of Agriculture
-- 
View this message in context: http://n4.nabble.com/Yet-another-question-about-importing-Excel-xls-files-tp1018699p1049793.html
Sent from the R help mailing list archive at Nabble.com.



More information about the R-help mailing list