# 调用VBA将Excel文件转为PDF格式
library(RDCOMClient)
xlFile = "path/to/daily.xlsx" # 这里使用绝对路径
xlApp = COMCreate("Excel.Application")
xlApp[["Visible"]] = TRUE
wb = xlApp[["Workbooks"]]$Open(Filename = xlFile)
sht = wb[["Worksheets"]]$Item(1)
sht$Select()
pdfFile = "path/to/daily.pdf" # 这里使用绝对路径
if (file.exists(pdfFile) == TRUE) file.remove(pdFile)
xlApp[["ActiveSheet"]]$ExportAsFixedFormat(
IgnorePrintAreas = FALSE,
Type = 0, # 输出为PDF
Filename = pdfFile
)
xlApp$Quit() # 关闭Excel文件
特别需要注意的是:
1.RDCOMClient包貌似不支持相对路径。
2.如果已经生成了PDF文件,如果再运行一遍程序,原先生成的PDF文件不会被覆盖,程序会报错,所以必须删除之前已经生成的PDF文件再运行程序。