Возможность комбинировать openxlsx-Workbook и xl_add_vg из rvg - Экспорт редактируемой графики - PullRequest
3 голосов
/ 23 сентября 2019

Я хочу экспортировать некоторые таблицы и графику ggplot из блестящего приложения в excel-файл.До сих пор я работал с openxlsx, добавляя много листов и контента.Теперь я хочу экспортировать ggplot как редактируемую векторную графику в Excel.Это вполне выполнимо с помощью rvg / офицер-пакетов.Есть ли возможность объединить это?Я хочу добавить лист с этой редактируемой графикой в ​​файл Excel, созданный openxlsx, с большим содержанием.До сих пор я могу реализовать это только независимо, соответственно, в двух отдельных файлах.

    library(shiny)
    library(ggplot2)
    library(openxlsx)
    library(officer)
    library(rvg)


    ui <- fluidPage(
      plotOutput("plot", height = "350px"),
      downloadButton('Export', label = 'Export as png in xlsx'),
      downloadButton('Export2', label = 'Export as editable xlsx')
    )
    server <- function(input, output) {
      # some plot
      plot <- ggplot(mpg, aes(x = class, fill = drv)) + 
        geom_bar(position = "stack")
      output$plot <- renderPlot({
          print(plot)
      })
      # Export plot as png in xlsx
      output$Export <- downloadHandler(
        filename = function() {
            paste0("someNicePlot", ".xlsx")
        },
        content = function(file) {
          wb <- createWorkbook()
          addWorksheet(wb, "someNicePlot", gridLines = F)
          ggsave("plot.png", plot = plot, width = 5, height = 5)
          insertImage(wb, "someNicePlot", "plot.png", width = 5, height = 5)
          # add some more worksheets and content
          saveWorkbook(wb, file)
        }
      ) 
      # Export plot as editable graphic in xlsx
      output$Export2 <- downloadHandler(
        filename = function() {
          paste0("someNicePlot_editable", ".xlsx")
        },
        content = function(file) {
          wb <- read_xlsx()
          # unfortunately the first sheet is named in french (from template)
          wb <- xl_add_vg(wb, sheet = "Feuil1",
                          code = print(plot), width = 5, height = 5, left = 1, top = 2 )
          print(wb, target = file)
        }
      ) 
    }

    shinyApp(ui, server)

1 Ответ

2 голосов
/ 23 сентября 2019

Вы можете создать временный xlsx-файл с содержимым из library(openxlsx) и прочитать его обратно, используя library(officer), отредактировать его (добавить другой лист) и, наконец, передать его в downloadHandler:

library(shiny)
library(ggplot2)
library(openxlsx)
library(officer)
library(rvg)

ui <- fluidPage(
  plotOutput("plot", height = "350px"),
  downloadButton('Export', label = 'Export as png in xlsx')
)

server <- function(input, output) {
  # some plot
  plot <- ggplot(mpg, aes(x = class, fill = drv)) + 
    geom_bar(position = "stack")
  output$plot <- renderPlot({
    print(plot)
  })
  # Export plot as png in xlsx
  output$Export <- downloadHandler(
    filename = function() {
      paste0("someNiceCombination", ".xlsx")
    },
    content = function(file) {

      openxlsxwb <- createWorkbook()
      addWorksheet(openxlsxwb, "someNicePlot", gridLines = F)
      ggsave("plot.png", plot = plot, width = 5, height = 5)
      insertImage(openxlsxwb, "someNicePlot", "plot.png", width = 5, height = 5)
      # add some more worksheets and content
      tmpwb <- tempfile(fileext = ".xlsx")
      saveWorkbook(openxlsxwb, tmpwb)

      # Export plot as editable graphic in xlsx
      officerwb <- read_xlsx(tmpwb)
      file.remove(tmpwb)
      officerwb <- add_sheet(officerwb, label = "someNicePlot_editable")
      officerwb <- xl_add_vg(officerwb, sheet = "someNicePlot_editable",
                             code = print(plot), width = 5, height = 5, left = 1, top = 2 )
      print(officerwb, target = file)
    }
  )
}

shinyApp(ui, server)
...