将损坏的 xls 文件加载到 r 而无需手动更改文件类型

load corrupted xls file into r without manually changing file type

我正在努力下载 excel 文件然后将其加载到 R:

utils::download.file(
  url = 'https://servicos.ibama.gov.br/ctf/publico/areasembargadas/downloadListaAreasEmbargadas.php',
  destfile = 'C:/users/arthu/Desktop/fines.rar',
  mode = "wb"
)

解压缩并尝试将其加载到 R 后:

utils::unzip(
  zipfile = './fines.rar',
  exdir = './ibama_data'
)


dados <- readxl::read_xls(
  "./ibama_data/rel_areas_embargadas_0-65000_2020-12-10_080019.xls"),
  skip = 6,
  col_type = c(rep("guess", 13), "date", "guess", "date")
)

我得到 libxls error: Unable to open file

如果我尝试按如下方式将文件重命名为 .xlsx,在使用 readxl::read_excel 读取文件时出现评估错误,显示 unable to open file

 file <-   file.rename(
      from = "./Desktop/ibama_data/rel_areas_embargadas_0-65000_2020-12-10_080019.xls",
      to = "./Desktop/ibama_data/test.xlsx"
    )

但是,如果我手动打开这样的文件,excel 会向我发出警告,指出文件的扩展名与其类型不匹配。将其保存为 .xlsx 后,我终于可以使用 read_excel

加载它

鉴于我想编写一个具有从网络下载此类数据然后将其加载到 R 中的功能的程序包,我该如何解决这个问题?

编辑

您尝试读取的 .xls 文件不是 Excel 文档,它是 HTML table.
您可以使用 XML 包阅读它:

library(XML)
doc <- htmlParse('rel_areas_embargadas_0-65000_2021-01-13_080018.xls')
tableNode <- getNodeSet(doc, '//table')
data <- XML::readHTMLTable(tableNode[[1]])

#Store header
header <- data[1:5,]

#Store colnames
colnames <- data[6,]

#Remove header
data <- data[-1:-6,]

#Set colnames
colnames(data)<-colnames

head(data)