首页 > 解决方案 > download.file 下载的 xlsx 文件无法打开

问题描述

我正在尝试使用 download.file 下载 xlsx 文件(该文件恰好位于 Teams 链接上),当我尝试查看文件时(在 R 中或只是在 Windows 中双击文件)它可以工作并下载一些东西资源管理器)它失败了。

然后我在 Dropbox 链接上对其进行了测试,但同样失败了(代码如下)。不知道为什么,但我尝试过没有显式模式和 mode="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",但这在这里没有影响(在任何一种模式下都不起作用)。

上面的链接确实有一个用于测试的文件,以防您想使用它。非常感谢

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

从 R 中的 URL 下载和读取 Excel 文件时出错

基于

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)

标签: rexceldownloadxlsx

解决方案


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

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。似乎默认情况下至少在我的 Windows pc 上download.file的文件夹中写入。~/Downloads

另一种方法也有效:

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

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


推荐阅读