r - 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"
,但这在这里没有影响(在任何一种模式下都不起作用)。
上面的链接确实有一个用于测试的文件,以防您想使用它。非常感谢
我还尝试了在这里找到的变体
基于
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)
解决方案
对问题的两条评论都解决了我电脑上的问题。
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.file
和read_excel
。似乎默认情况下至少在我的 Windows pc 上download.file
的文件夹中写入。~/Downloads
另一种方法也有效:
library(httr)
GET(url, write_disk(fn, overwrite=TRUE))
dat <- read_excel(fn)
请注意,这data
也是一个基本 R 函数,因此使用该名称命名变量不是一个好主意。
推荐阅读
- reactjs - React,chrome 性能选项卡中没有用户代码的源映射,
- sql - 替换 SQL 不存在
- javascript - 我想创建一个按钮,该按钮将仅使用 HTML、css 和 JavaScript 将音乐文件从用户计算机加载到 div。那可能吗?
- java - 运行 gradlew.bat 和设置开发环境的问题
- r - 如何使用 ifTHEN 语句
- java - C# 中的 Java.Lang GetClass
- python - Plotly:Dash 如何在没有导入 plotly 或 plotly express 的情况下描述数据
- javascript - 我想使用位置功能向#cart-total-remove 添加一个类我尝试了很多方法但没有奏效
- excel - 根据来自其他单元格的匹配名称填充单元格
- powershell - 外壳 | 如何以编程方式遍历变量名