Search code examples
rvbaexcelxlsx

How to export an Excel sheet range to a picture, from within R


We are trying to automate the creation of some picture files within an R Script.

We have the Excel files looking the way that we want them to, but now need to make a JPG or PNG picture-copy of those excel tables for easier web posting.

We've been using the library(xlsx) package for most of our interactions between R and Excel, and it looks like we should be able to send specific java commands through something like ?.jmethods but it's unclear how we would pass as many lines as we need to.

In an R session, here's a minimal reproducible example...

Here's an example Excel file with a range to print

library(xlsx)
file <- system.file("tests", "test_import.xlsx", package = "xlsx")
file

And here's the Excel macro that exports the Excel range to a picture file

Sub Tester()

    Worksheets("deletedFields").Range("A8:J36").CopyPicture xlScreen, xlBitmap

    Application.DisplayAlerts = False
    Set oCht = Charts.Add
    With oCht
        .Paste
        .Export Filename:="C:\temp\SavedRange.jpg", Filtername:="JPG"
        .Delete
    End With


End Sub

Any help automating this would be much appreciated!


Solution

  • Consider having R do exactly as VBA does in your macro: making a COM interface to the Excel object library. You can do so with the RDCOMClient package, retaining nearly same code as macro in the R syntax.

    library(RDCOMClient)
    
    xlApp <- COMCreate("Excel.Application")
    xlWbk <- xlApp$Workbooks()$Open("C:\\Path\\To\\test_import.xlsx")
    xlScreen = 1
    xlBitmap = 2
    
    xlWbk$Worksheets("deletedFields")$Range("A8:J36")$CopyPicture(xlScreen, xlBitmap)
    
    xlApp[['DisplayAlerts']] <- FALSE
    
    oCht <- xlApp[['Charts']]$Add()
    oCht$Paste()
    oCht$Export("C:\\Temp\\SavedRange.jpg", "JPG")
    oCht$Delete()
    
    # CLOSE WORKBOOK AND APP
    xlWbk$Close(FALSE)
    xlApp$Quit()
    
    # RELEASE RESOURCES
    oCht <- xlWbk <- xlApp <- NULL    
    rm(oCht, xlWbk, xlApp)
    gc()
    

    Output (random data/chart)

    Data and Chart Output Image