使用R下载Excel文件

时间:2017-10-03 20:30:07

标签: r excel downloadfile

我正在尝试从哥伦比亚中央银行网站下载一个Excel文件,但似乎通常的download.file功能无法完成这项工作。

例如,我正在尝试下载此页面上的第一个文件“Serie historica”:http://www.banrep.gov.co/es/indice-tasa-cambio-real

该文件的链接如下所示,我在download.file函数中使用了该链接 http://obieebr.banrep.gov.co/analytics/saw.dll?Download&Format=excel2007&Extension=.xls&BypassCache=true&path=%2Fshared%2FSeries%20Estad%c3%adsticas_T%2F1.%20Indice%20de%20Tasa%20de%20Cambio%20Real%2F1.1.%20Serie%20historica_IQY&SyncOperation=1&NQUser=publico&NQPassword=publico

我使用的命令是: download.file(filepath,destfile,quiet = FALSE,mode =“wb”)

非常感谢任何帮助!

3 个答案:

答案 0 :(得分:2)

我希望这个例子可以指导你

library(readxl)
library(httr)
url1<-'https://evs.nci.nih.gov/ftp1/CDISC/SDTM/SDTM%20Terminology.xls'
GET(url1, write_disk(tf <- tempfile(fileext = ".xls")))
df <- read_excel(tf, 2L)
str(df)

如果您可以下载文件,可以按如下方式阅读

library(readxl)
datos <- read_xlsx("C:/Users/USER/Downloads/1.1. Serie historica_IQY.xlsx", skip = 8, n_max = 369)

答案 1 :(得分:1)

如果您使用的是windows,请考虑使用mode = "wb"

download.file("http://gapm.io/dl_pop",
              destfile = "data/pop1800_2100.xlsx",
              mode = "wb")

答案 2 :(得分:0)

答案有点晚了,但我认为仍然值得提供解决方案。

无法使用download.file函数,因为此链接实际上并没有直接指向文件。实际上,这是使用GET方法对API的查询,因此您应该使用其他代码结构来获取文件,这种情况对于使用网络抓取技术的用户可能会反复发生

我分享了一个如何获取每日COLCAP索引的excel文件的示例:

url <- 'http://obieebr.banrep.gov.co/analytics/saw.dll?Download&Format=excel2007&Extension=.xlsx&BypassCache=true&Path=%2fshared%2fSeries%20Estad%c3%adsticas_T%2f1.%20%c3%8dndices%20de%20mercado%20burs%c3%a1til%20colombiano%2f1.1.%20IGBC,%20IBB%20e%20IBOMED%2f1.1.1.IMBC_COLCAP%20IQY&lang=es&NQUser=publico&NQPassword=publico&SyncOperation=1'

content_type = "text/html; charset=utf-8"
while (content_type == "text/html; charset=utf-8") {
  request <- GET(url,
                 add_headers(`Accept` = 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
                             `Accept-Encoding` = 'gzip, deflate',
                             `Accept-Language` = 'es-ES,es;q=0.9',
                             `Connection` = 'keep-alive',
                             `Host` = 'obieebr.banrep.gov.co',
                             `User-Agent` = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36'),
                 write_disk("COLCAP_daily.xlsx", overwrite = T),
                 verbose()
  )
  content_type = request$all_headers[[1]]$headers$`content-type`
}

我希望该示例对您有所帮助,如果您仍然有疑问,我们可以对其进行更详细的审查。问候。

相关问题