使用R将Excel (.xlsx)表格打印/保存为PDF

5

我想在编辑Excel文件后将其打印成pdf文件。我使用过.xlsx包进行编辑,效果不错。有一个printSetup函数,但我找不到开始打印的函数。是否有解决方法?

library(xlsx)
file <- "test.xlsx"
wb <- loadWorkbook(file)  
sheets <- getSheets(wb)       # get all sheets
sheet <- sheets[[1]]          # get first sheet
# HERE: MAGIC TO SAVE THIS SHEET TO PDF

这可能是通过RDCOMClient包使用DCOM的解决方案,但我更喜欢跨平台的解决方案(例如使用xlsx),因为我使用的是 MacOS。有什么想法吗?

3个回答

5

以下是使用 RDCOMClient 通过 DCOM 接口的解决方案。这不是我首选的解决方案,因为它只适用于 Windows。我们仍然需要一个跨平台的解决方案。

library(RDCOMClient)
library(R.utils)

file <- "file.xlsx"                   # relative 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="my.pdf", 
                                        IgnorePrintAreas=FALSE)
ex[["ActiveWorkbook"]]$Save()         # save workbook
ex$Quit()                             # close Excel

我认为RDCOM不再可用。 - igorkf
1
RDCOMClient安装问题(在R 3.6上) - captcoma

3

一种开源且跨平台的方式是使用LibreOffice,如下所示:

library("XLConnect")
x <- rnorm(1:100)
y <- x ^ 2
writeWorksheetToFile("test.xlsx", data.frame(x = x, y = y), "Data")
tmpDir <- file.path(tempdir(), "LOConv")
system2("libreoffice", c(paste0("-env:UserInstallation=file://", tmpDir), "--headless", "--convert-to pdf",
    "--outdir", getwd(), file.path(getwd(),"test.xlsx")))

理想情况下,您应该删除tmpDir引用的文件夹,但这将是特定于平台的。
请注意,这假设libreoffice在您的路径中。如果不是,则需要修改命令以包括libreoffice可执行文件的完整路径。
env部分的原因是无头libreoffice只有在它没有在GUI模式下运行时才会做任何事情。有关更多信息,请参见http://ask.libreoffice.org/en/question/1686/how-to-not-connect-to-a-running-instance/

我无法让上述内容为我工作。我已将libreoffice / program添加到我的路径中,并用“soffice”替换了“libreoffice”,但命令似乎一直在运行。有什么见解吗? - GerasimosPanagiotakopoulos
经过进一步的研究,我怀疑tmpDir与我的引导文件内容不一致。这是答案与Libreoffice设置或我的平台(Windows)不兼容的问题吗? - GerasimosPanagiotakopoulos

-4
您可以使用pdf函数:
pdf(file="myfile.pdf", width=8.5, height=11)
print(firstsheet)
grid.newpage()
print(secondsheet)
grid.newpage()
print(thirdsheet)
dev.off()

jobjRef对象的打印方法将返回一个字符串。这该如何工作? - Mark Heckmann

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接