Link excel database with downloadLink in Shiny

折月煮酒 提交于 2020-06-23 12:19:42

问题


Could you help me link an excel database to my downloadLink? Therefore, whenever I click on "Download the standard base" in shiny, an excel database is automatically downloaded. I made a minimal example below just to show the idea. I don't know how to adjust it on my server for this to work correctly.

Thank you!

library(shiny)

ui <- fluidPage(

    titlePanel("Old Faithful Geyser Data"),
    sidebarLayout(
        sidebarPanel(

            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30),
            downloadLink("standarddatabase", h4("Download the standard base")),
              ),

        mainPanel(
           plotOutput("distPlot")
        )
    )
)

server <- function(input, output) {

    output$distPlot <- renderPlot({
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

       hist(x, breaks = bins, col = 'darkgray', border = 'white')
    })
}

shinyApp(ui = ui, server = server)


回答1:


library(shiny)
#install.packages("xlsx", dependencies = TRUE)
library(xlsx)
ui <- fluidPage(

    titlePanel("Old Faithful Geyser Data"),
    sidebarLayout(
        sidebarPanel(

            sliderInput("bins",
                        "Number of bins:",
                        min = 1,
                        max = 50,
                        value = 30),
            downloadButton("downloadData", "Download Standard Database"),
        ),

        mainPanel(
            plotOutput("distPlot")
        )
    )
)

server <- function(input, output) {

    output$distPlot <- renderPlot({
        x    <- faithful[, 2]
        bins <- seq(min(x), max(x), length.out = input$bins + 1)

        hist(x, breaks = bins, col = 'darkgray', border = 'white')
    })


    # Reactive value for selected dataset ----
    datasetInput <- reactive({
        switch(faithful,
               "eruptions" = eruptions,
               "waiting" = waiting)
    })

    # Table of selected dataset ----
    output$table <- renderTable({
        faithful
    })

    # Downloadable csv of selected dataset ----
    output$downloadData <- downloadHandler(
        filename = function() {
            paste0(deparse(substitute(faithful)), ".xlsx")
        },
        content = function(file) {
            write.xlsx(as.data.frame(faithful), file, 
                       sheetName = deparse(substitute(faithful)),
                       row.names = FALSE)
        }
    )
}

shinyApp(ui = ui, server = server)


来源:https://stackoverflow.com/questions/62458565/link-excel-database-with-downloadlink-in-shiny

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