如何在 R 中下载 .xlsx 文件并将数据加载到数据框中?

How to download an .xlsx file in R and load the data into a dataframe?

我正在尝试从 eia 下载 .xlsx 文件并收到以下错误。

错误是:"Error: ZipException (Java): invalid entry size (expected 2385 but got 2390 bytes)"

我试过以下代码:

library(XLConnect)
tmp = tempfile(fileext = ".xlsx")
download.file(url = "http://www.eia.gov/petroleum/drilling/xls/dpr-data.xlsx", destfile = tmp)
readWorksheetFromFile(file = tmp, sheet = "Eagle Ford Region", header = FALSE, startRow = 9, endRow = 151)

我已经在以下位置尝试了其他建议: Read Excel file into R with XLConnect package from URL

您应该使用 wb - 下载非纯文本文件时的二进制模式:

download.file(url = "http://www.eia.gov/petroleum/drilling/xls/dpr-data.xlsx", destfile = tmp, mode="wb")

这将解决问题。

我真的来晚了,但我花了很多时间在同一个错误上,这对我不起作用。如果您只是为了使用 read_xlsx 从磁盘加载文件而尝试下载文件,更好的解决方案是完全跳过磁盘步骤:

# install.packages(rio)
library(rio)

data = rio::import(url)

干杯