简体   繁体   English

以 csv 格式下载生成的表格 - R Shiny

[英]Download the generated table in a csv format - R shiny

My shiny app generates a table that I want to make available for download in a csv format.我闪亮的应用程序生成了一个表格,我想以 csv 格式提供该表格供下载。

  ui = fluidPage( ...
         tableOutput("contents"),
         downloadButton("download", "Download results in csv format") 
)
server <- function( input, output, session ) {
   
   output$contents <- renderTable( ... )
  

output$download <- downloadHandler(
    filename = function() {
      paste(contents, ".csv", sep = "")
    },
    content = function(file) {
      write.csv(contents(), file, row.names = FALSE)
    }
  )

I understand that I have to create a reactive object, but the renderTable itself uses another reactive object (uploaded dataset), so it looks like I need to nest one reactive object into another, and it does not seem to work.我知道我必须创建一个反应式对象,但是renderTable本身使用另一个反应式对象(上传的数据集),所以看起来我需要将一个反应式对象嵌套到另一个中,但它似乎不起作用。 Will appreciate any help.将不胜感激任何帮助。 Thank you!谢谢!

EDIT: Added an example using renderTable instead of renderDataTable , as requested by the question and in the comment section:编辑:根据问题和评论部分的要求,添加了一个使用renderTable而不是renderDataTable的示例:

Here is an example using the iris dataset.这是一个使用 iris 数据集的示例。 I also added a table from the DT package.我还从 DT 包中添加了一个表。 You should not paste the data in the filename function, only in the in the write.csv function.您不应将数据粘贴到filename函数中,而应粘贴到write.csv函数中。

```{r}
library(shinydashboard)
library(dplyr)
library(DT)

```
setosa <- filter(iris, Species == "setosa")

ui = fluidPage(
  downloadButton("download", "Download results in csv format") ,
  column(12,
         DT::dataTableOutput ("content"),
         style = "  overflow-y: scroll;overflow-x: scroll;")
  
)

server <- function(input, output, session) {
  output$content <-
    renderDataTable(head(setosa))
  output$download <-
    downloadHandler(
      filename = function () {
        paste("MyData.csv", sep = "")
      },
      content = function(file) {
        write.csv(content, file)
      }
    )
}

shinyApp(ui, server)
```

Using renderTable instead of renderDataTable使用renderTable而不是renderDataTable


library(shiny)
library(dplyr)
library(DT)


setosa <- filter(iris, Species == "setosa")

ui = fluidPage(
  downloadButton("download", "Download results in csv format"),
   tableOutput("table")

  
)

server <- function(input, output, session) {
  data <- data.frame(setosa)
  output$table <-
    renderTable(data)
  output$download <-
    downloadHandler(
      filename = function () {
        paste("MyData.csv", sep = "")
      },
      
      content = function(file) {
        write.csv(data, file)
      }
    )
}

shinyApp(ui, server)

在此处输入图片说明 在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM