You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

R读取下载的xlsx文件报错,求批量自动化解决方法

解决R中下载的xlsx文件无法用read.xlsx读取的问题

问题背景

我通过以下R代码从希腊统计局网站下载xlsx文件:

links <- 
  read_html("https://www.statistics.gr/en/statistics/-/publication/DKT90/-") |> 
  html_elements(xpath ="(//table[@class='documentsTable'])[last()]//a")

links2<-tibble::tibble(
  text = html_text(links) |> tibble::char(min_chars = 20),
  href = html_attr(links, "href") |> tibble::char(min_chars = 50),
) 

url3_gr<-links2$href[1] %>% as.character()

destination<- "file.xlsx"
download.file(url3_gr, destination, mode = "wb")  

下载过程无异常,但使用read.xlsx("file.xlsx")读取时触发报错:

Error in file(con, "r") : invalid 'description' argument
In addition: Warning message:
In unzip(xlsxFile, exdir = xmlDir) : error 1 in extracting from zip file

手动打开文件重新保存为xlsx即可恢复正常,但文件数量较多时手动操作效率极低,需要自动化解决方案。

解决方案

问题根源是下载的文件并非标准xlsx格式(可能是xls伪装、编码异常或压缩结构不规范),以下两种方法可自动化解决:

方法1:使用readxl包直接读取

readxl::read_excel对非标准Excel格式兼容性更强,无需修复即可直接读取:

library(readxl)
# 下载后直接读取文件
df <- read_excel("file.xlsx")

方法2:修复文件后用read.xlsx读取

若必须使用read.xlsx,可通过openxlsx包先解析并重新保存为标准xlsx:

library(openxlsx)
# 加载下载的非标准文件
wb <- loadWorkbook("file.xlsx")
# 重新保存为规范xlsx
saveWorkbook(wb, "fixed_file.xlsx", overwrite = TRUE)
# 再用read.xlsx读取修复后的文件
df <- read.xlsx("fixed_file.xlsx")

批量处理整合方案

将下载、修复、读取流程整合,实现批量自动化处理:

library(rvest)
library(tibble)
library(openxlsx)

# 获取目标链接列表
links <- 
  read_html("https://www.statistics.gr/en/statistics/-/publication/DKT90/-") |> 
  html_elements(xpath ="(//table[@class='documentsTable'])[last()]//a")

links2 <- tibble(
  text = html_text(links) |> char(min_chars = 20),
  href = html_attr(links, "href") |> char(min_chars = 50),
) 

# 遍历处理每个文件
for (i in seq_len(nrow(links2))) {
  url <- as.character(links2$href[i])
  temp_file <- tempfile(fileext = ".xlsx")
  
  # 下载文件
  download.file(url, temp_file, mode = "wb")
  
  # 修复并保存标准xlsx
  wb <- loadWorkbook(temp_file)
  output_file <- paste0("fixed_", gsub("\\.xlsx$", "", basename(url)), ".xlsx")
  saveWorkbook(wb, output_file, overwrite = TRUE)
  
  # 读取数据(可添加后续分析/存储逻辑)
  df <- read.xlsx(output_file)
  print(paste("完成处理:", links2$text[i]))
}

原理说明

  • readxl内部会自动识别并解析多种Excel格式变体,跳过手动修复步骤
  • openxlsx的loadWorkbook能兼容非标准xlsx的结构,重新保存时会生成符合OOXML规范的文件,解决解压错误问题
  • 使用tempfile临时存储下载文件,避免批量处理时的命名冲突

内容的提问来源于stack exchange,提问作者nickcox896

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.11 15:03:24