我是Shiny的新手,我创造了一个非常简单的闪亮应用程序:
library(shiny)
ui <- fluidPage(
fluidRow(column(7,dataTableOutput('dto')))
)
server <- function(input,output){
output$dto <- renderDataTable({MYTABLE})
}
runApp(list(ui=ui,server=server))
Run Code Online (Sandbox Code Playgroud)
有没有办法放一个选项来下载表的结果(如果是CSV,XLSX则无关紧要......)
干杯
Jor*_*eys 13
如果您将数据本身作为反应式表达,那么这很容易downloadButton()或与之downloadLink()结合使用downloadHandler.然后,您可以使用相同的反应式表达式下载发送到输出的任何内容.
一个小例子:
library(shiny)
ui <- fluidPage(
# This one is linked by the id 'download'
downloadButton('download',"Download the data"),
fluidRow(column(7,dataTableOutput('dto')))
)
server <- function(input,output){
# Reactive expression with the data, in this case iris
thedata <- reactive(iris)
output$dto <- renderDataTable({thedata()})
output$download <- downloadHandler(
filename = function(){"thename.csv"},
content = function(fname){
write.csv(thedata(), fname)
}
)
}
runApp(list(ui=ui,server=server))
Run Code Online (Sandbox Code Playgroud)
记住:
content的downloadHandler必须是一个生成文件的功能!它应该为连接/文件名采用一个参数.在这个例子中它是一个CSV文件,但对于如图像,您可以使用png()和dev.off(),为ggplots可以使用ggsave(),...filename不一定是函数,但我发现它的工作方式更好.特别是在处理文件名的反应式表达式时.downloadHandler和downloadButton通过输出列表:id downloadButton是返回的输出元素的名称downloadHandler.编辑:
有些人试图用download.file()它,但这也是错的.该功能download.file()在用户端而非服务器端使用时有效.它允许您将文件从Internet下载到调用该功能的计算机.如果你在Shiny应用程序中使用它,它将在本地运行时工作.那是因为用户和服务器是同一台机器.但是,在Shiny Server上部署应用程序时,download.file()主要是将文件下载到服务器,而不是从.
一种稍微替代的解决方案,直接基于datatable/ DTextension buttons.
我无耻地借用Joris的示例数据......
library(shiny)
library(DT)
ui <- fluidPage(
# This one is linked by the id 'download'
fluidRow(column(7,dataTableOutput('dto')))
)
server <- function(input,output){
# Reactive expression with the data, in this case iris
thedata <- reactive(iris)
#the extensions parameter coupled with the options list does the trick
output$dto <- renderDataTable(thedata(), extensions = 'Buttons',
options = list(dom = 'Bfrtip',
buttons = c('copy', 'csv', 'excel', 'pdf', 'print'))
)
}
runApp(list(ui=ui,server=server), launch.browser=TRUE) #now runs by default in the external browser.
Run Code Online (Sandbox Code Playgroud)
这将适用于不同的输出,我个人喜欢更干净的外观.只需确保您在外部浏览器中运行演示.否则它将无法工作.
| 归档时间: |
|
| 查看次数: |
8893 次 |
| 最近记录: |