Download Selected Rows in DT

Viewed 804

Is there any way to download selected rows with buttons extension? If not, is there any way to add custom buttons within the table at top left side? I know how to download selected rows. I found we can add custom button to select columns (https://github.com/rstudio/DT/issues/397)

I added 2 custom buttons (mentioned in the code below).

library(shinydashboard)

header <- dashboardHeader(title = 'title')
sidebar <- dashboardSidebar(
  sidebarMenu(
    menuItem('dashboard', tabName = 'dashboard', icon = icon('dashboard'))
  )
)
body <- dashboardBody(
 fluidPage(fluidRow(
  column(2,   
      actionButton("downloadData", "Download Selected Rows", icon = icon("download"), 
      style="color: #333; background-color: #FFF; border-color: #333")),
      useShinyalert(),
      column(2,  
      actionButton(inputId = "run", label = "Write Selected Rows to SQL", icon = icon("paper-plane"),
                       style="color: #333; background-color: #FFF; border-color: #333")),
     useShinyalert()
  )),

           box(
             title = 'box', width = NULL, status = 'primary',
             DT::dataTableOutput('table2')  
  )
)

ui<-dashboardPage(header, sidebar, body)

server = function(input, output) {
  output$table2 = DT::renderDataTable(
    iris, options = list(lengthChange = FALSE)
  )
}

shinyApp(ui, server)
1 Answers

Not sure in which format you wish to download the selected rows, but here is an example storing a csv-file based on the selection (you need a downloadButton):

library(shiny)
library(shinyalert)
library(shinydashboard)

header <- dashboardHeader(title = 'title')
sidebar <- dashboardSidebar(
  sidebarMenu(
    menuItem('dashboard', tabName = 'dashboard', icon = icon('dashboard'))
  )
)
body <- dashboardBody(
  fluidPage(fluidRow(
    column(2,   
           downloadButton("downloadData", "Download Selected Rows", icon = icon("download"), 
                          style="color: #333; background-color: #FFF; border-color: #333")),
    useShinyalert(),
    column(2,  
           actionButton(inputId = "run", label = "Write Selected Rows to SQL", icon = icon("paper-plane"),
                        style="color: #333; background-color: #FFF; border-color: #333")),
    useShinyalert()
  )),
  p(),
  box(
    title = 'box', width = NULL, status = 'primary',
    DT::dataTableOutput('table2')  
  )
)

ui<-dashboardPage(header, sidebar, body)

server = function(input, output) {
  output$table2 = DT::renderDataTable(
    iris, options = list(lengthChange = FALSE)
  )

  output$downloadData <- downloadHandler(
    filename = function() {
      paste0(gsub(" ","_", gsub(":",".", Sys.time())),".csv")
    },
    content = function(file) {
      write.table(iris[input$table2_rows_selected,], file, row.names = FALSE)
    }
  )

}

shinyApp(ui, server)
Related