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

前端 未结 3 714
隐瞒了意图╮
隐瞒了意图╮ 2020-12-31 13:24

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

3条回答
  •  鱼传尺愫
    2020-12-31 14:06

    Hmm, not sure about posting, maybe it got redundant through Ian´s post. Its a bit more generic, but I can also remove it.

    library(xlsx)
    
    OutputPicFileName <- "Chart.jpg"
    ScriptFileName <- "Chart.vbs"
    xclFileName <- "test_import.xlsx"
    xclRng <- "A8:J36"
    file <- system.file("tests", xclFileName, package = "xlsx")
    fileDirec <- unlist(strsplit(file, xclFileName))
    
    CreateChart <- function(fileDirec, OutputPicFileName, ScriptFileName, xclRng){
      setwd(fileDirec)
      filePath <- file(paste0(fileDirec, ScriptFileName))
      writeLines(
        c(
          "Dim App, WBook, Sht, Rng, FileName, ChartObj, Chart",
           paste0("FileName = \"", gsub("/", "\\\\", fileDirec), xclFileName ,"\""),
           "Set App = CreateObject(\"Excel.Application\")",
           "Set WBook = App.WorkBooks.Open(FileName)",
           "Set Sht = App.Worksheets(1)",
           paste0("Set Rng = Sht.Range(\"", xclRng,"\")"),
           "Rng.CopyPicture",
           "Set ChartObj = App.Charts",
           "Set Chart = ChartObj.Add() ",
           "Chart.paste",
           paste0("Chart.Export \"", gsub("/", "\\\\", fileDirec) , OutputPicFileName ,"\", \"JPG\"")
        ), 
        filePath
      )
      close(filePath)
      shell.exec(ScriptFileName)
    }
    
    CreateChart(fileDirec, OutputPicFileName, ScriptFileName, xclRng)
    
    # Result in: fileDirec
    

提交回复
热议问题