How to download multiple reports created using R markdown and R shiny in a zip file

痞子三分冷 提交于 2019-12-07 21:44:30

Here is a reproducible example (to make it work, create an rmarkdown file with the default content using RStudio, and save it as "test.rmd" in the same folder as your Shiny app).

Important:

  • You need to run the app externally inside your web browser. Somehow it does not work in the viewer pane or RStudio window (you get the download window but then no file is saved).
  • If you are on Windows, you need to make sure that you install RTools first, and also put the rtools/bin folder in your system path.

app.R

library(shiny)

ui <- shinyUI(fluidPage(

  titlePanel("Old Faithful Geyser Data"),

  sidebarLayout(
    sidebarPanel(
      downloadButton("downloadData", "Download")
    ),

    mainPanel(
      DT::dataTableOutput('myTable1')
    )
  )
))

server <- shinyServer(function(input, output) {

  output$myTable1 <- DT::renderDataTable(iris)

  output$downloadData <- downloadHandler(
    filename = function() {
      paste0("output", ".zip")
    },
    content = function(file) {
      k <- input$myTable1_rows_selected
      fs <- c()
      for (i in k) {
        path <- paste0(i, ".docx")
        rmarkdown::render("test.rmd", rmarkdown::word_document(), output_file = path)
        fs <- c(fs, path)
      }
      zip(file, fs)
    },
    contentType = "application/zip"
  )

})

shinyApp(ui = ui, server = server)

Hello I also installed Rtools/bin and was running the code on the web browser, but when I click on download button, download window doesn't comes up and shows '404 Not Found', but when I check the directory, the doc files report are saving directly to directory, no zip file is produced. Please see below code.

ui <- {
tagList(
div(id = "downloadBtn",
    downloadButton("downloadData", "Download")),
DT::dataTableOutput('myTable1')   
)
}

dataJ <- read.csv(file = "iris.csv", header = TRUE, stringsAsFactors =           
                FALSE)
server <- function(input, output)
{
output$myTable1 <- DT::renderDataTable({
DT::datatable(dataJ, options = list(orderClasses = TRUE), filter = 'top')})
output$downloadData <- downloadHandler(

filename = ("output.zip"),


content = function(file) 
{

k <- (input$myTable1_rows_selected)
fs <- c()
for ( i in k) 
  {
  path <- paste0(i,".docx")
  rmarkdown::render("R_markdown_script.Rmd", output_file = path , 
  params = list(j=i), envir = new.env(parent = globalenv()))

  fs <- c(fs,file)
  }
zip(zipfile = file, files = fs)

  }, 
  contentType = "application/zip" )
}

runApp(list(ui = ui, server = server))`
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!