下载DT中的选定行

时间:2018-10-22 14:27:16

标签: shiny dt

是否可以下载扩展名为buttons的所选行?如果没有,是否有任何方法可以在左上方的表格中添加自定义按钮?我知道如何下载选定的行。我发现我们可以添加自定义按钮来选择列(https://github.com/rstudio/DT/issues/397

我添加了2个自定义按钮(在下面的代码中提到)。

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 个答案:

答案 0 :(得分:0)

不确定要以哪种格式下载选定的行,但是下面是一个基于选择存储csv文件的示例(您需要一个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)