由download.file下载的xlsx文件无法打开

时间:2020-06-21 02:55:54

标签: r excel download xlsx

我正在尝试使用download.file下载xlsx文件(该文件恰好在Teams链接上),并且当我尝试查看该文件时(在R中,或者双击Windows资源管理器中的文件)失败。

然后我在一个保管箱链接上对其进行了测试,但同样失败(下面的代码)。不知道为什么,但是我尝试了不带显式模式和带模式=“ wb”的情况。

示例代码:

download.file(
    url = "https://www.dropbox.com/s/9bumheqlbpxygnl/testfile.xlsx?dl=0", 
    destfile = "test.xlsx",
    mode="wb"
)   

我读取下载的文件时出错:

> readxl::read_xlsx("test.xlsx")
Error: Evaluation error: zip file 'C:\Users\tam2\Dropbox\Trabalho\CEAUL\COVID19\Projetos\COVIDETECT\dados\test.xlsx' cannot be opened.

有人可以帮助我了解发生了什么吗?我在StackOverflow上看到其他人通过使用mode="wb"解决了他们的问题,但这对这里没有影响(在任何一种模式下均不起作用)。

上面的链接中确实包含一个用于测试的文件,以备您使用时使用。非常感谢

我还尝试了在这里找到的变体

Error downloading and reading Excel file from URL in R

基于

library(httr)
GET("https://www.dropbox.com/s/9bumheqlbpxygnl/testfile.xlsx?dl=0", write_disk(tf <- tempfile(fileext = ".xls")))
data <- read_excel(tf)

但又撞到了石墙

Error: 
  filepath: C:\Users\tam2\AppData\Local\Temp\RtmpCA2uEa\file31802e134f09.xls
  libxls error: Unable to open file
R version 3.6.3 (2020-02-29) -- "Holding the Windsock"
Copyright (C) 2020 The R Foundation for Statistical Computing
Platform: x86_64-w64-mingw32/x64 (64-bit)

1 个答案:

答案 0 :(得分:0)

对问题的两条评论都可以解决我电脑上的问题。

url <- "https://www.dropbox.com/s/9bumheqlbpxygnl/testfile.xlsx?dl=1"
fn <- tempfile(fileext=".xlsx")
download.file(url, destfile=fn, mode="wb")
library(readxl)
dat <- read_excel(fn)
str(dat)

请注意,URL已更改为dl=1,并提供了到download.fileread_excel的完整路径。看来download.file至少在我的Windows pc上至少在这里写入~/Downloads文件夹中。

另一种方法也有效:

library(httr)
GET(url, write_disk(fn, overwrite=TRUE))
dat <- read_excel(fn)

请注意,data也是R函数的基础,因此用该名称命名变量不是一个好主意。