【问题标题】:Batch convert Excel files to PDFs in R在 R 中将 Excel 文件批量转换为 PDF
【发布时间】:2020-01-15 02:05:17
【问题描述】:

我有一个 Excel (xlsx) 工作表文件夹,我想在 R 中将其转换为 PDF。我尝试将工作表直接读入 R(使用几乎所有包),但数据从未正确读取。我正在处理来自几个不同人的 excel 电子表格,因此假设这是因为从每个人的计算机保存文件之间存在差异。

我认为将这些文件转换为 PDF 意味着它们的格式都相同,因此更易于使用。

是否可以使用 R 将文件从 excel 工作表转换为 PDF,而无需打开文件/将它们读入 R,因为这是发生错误的地方?

【问题讨论】:

  • @captcoma RDCOMClient 不适用于我的 R 版本(3.6.2),第二个答案将数据读入 R,所以很遗憾,这不是我想要的。跨度>
  • 可以从 omegahat.net 获得兼容版本的 RDCOMClient。查看下面的脚本。

标签: r excel rstudio


【解决方案1】:

这应该适用于 R 3.6.2:

# install RDCOMClient for 3.6.2
url <- "http://www.omegahat.net/R/bin/windows/contrib/3.5.1/RDCOMClient_0.93-0.zip"
install.packages(url, repos=NULL, type="binary")

# install R.utils
install.packages("R.utils")

library(RDCOMClient)
library(R.utils)

# make a list of the folder with your excel files
# replace "Path to your folder" with the path to your folder
list.files("Path to your folder",full.names=TRUE) -> list

# Batch convert (replace "Path to your folder" with the path to your folder)
lapply(list, function(x) {

file <- x                             # path to Excel file
ex <- COMCreate("Excel.Application")  # create COM object
file <- getAbsolutePath(file)         # convert to absolute path
book <- ex$workbooks()$Open(file)     # open Excel file
sheet <- book$Worksheets()$Item(1)    # pointer to first worksheet
sheet$Select()                        # select first worksheet
ex[["ActiveSheet"]]$ExportAsFixedFormat(Type=0,    # export as PDF
                                        Filename=paste0("Path to your folder",gsub(pattern = "\\.xlsx$", "", basename(x)),".pdf"), 
                                        IgnorePrintAreas=FALSE)
ex[["ActiveWorkbook"]]$Save()         # save workbook
ex$Quit()                             # close Excel
})

【讨论】:

  • 感谢您的回复。我得到Error: Exception occured. 我通过循环运行browser() 并发现它在sheet$Select() @captcoma 引发了异常
  • 您是否在较小的文件子集上进行了尝试?您的一份文件可能已损坏。
  • 您使用哪种操作系统?
  • 我使用的是 Windows 10 :)
  • 试试:sheet &lt;- book$Worksheets(1)
猜你喜欢
  • 1970-01-01
  • 2019-01-04
  • 1970-01-01
  • 2014-04-02
  • 2016-04-07
  • 2011-06-25
  • 1970-01-01
  • 2012-11-30
  • 2014-12-03
相关资源
最近更新 更多