r - 使用 Shiny 将用户输入和表格导出到一个 Excel 文件
问题描述
我编写了一个应用程序,允许用户提供一些输入。该应用程序将调用一个函数来进行一些计算并以表格格式生成输出。
我想添加一个按钮,允许用户将输入和输出下载到 Excel 电子表格中(带有两个选项卡)
下面是我要下载输入和示例表的代码的简化版本。我尝试了以下代码但失败了:
library(shiny)
library(openxlsx)
somefunction <- function() {
data.frame(text = c("sample1","sample2"))}
server <- function(input, output, session) {
dataReactive <- reactive({
data.frame(text = c(input$text1, input$text2, input$text3))
})
observeEvent(input$goButton,{
output$exampleTable <- DT::renderDataTable({somefunction()})
})
output$downloadExcelSheet <- downloadHandler(
filename = function() {
paste("result",Sys.Date(), ".xlsx",sep="")
},
content = function(file) {
write.xlsx(list(dataReactive(),exampleTable), file)
})
}
ui <- fluidPage(
sidebarLayout(
sidebarPanel(
textInput("text1","Text 1:",value="Input 1"),
textInput("text2","Text 2:",value="Input 2"),
actionButton("goButton", "Calculate"),
downloadButton("downloadExcelSheet", "Download Data")
),
mainPanel(
DT::dataTableOutput("exampleTable")
)
)
)
shinyApp(ui = ui, server = server)
解决方案
server <- function(input, output, session) {
dataReactive <- reactive({
data.frame(text = c(input$text1, input$text2, input$text3))
})
data <- reactiveValues()
observeEvent(input$goButton,{
output$exampleTable <- DT::renderDataTable({
data$df <- somefunction()
})
})
output$downloadExcelSheet <- downloadHandler(
filename = function() {
paste("result",Sys.Date(), ".xlsx",sep="")
},
content = function(file) {
write.xlsx(list(dataReactive(),data$df), file)
})
}
最好像这样搬到外面data$df <- somefunction()
去observeEvent
DT::renderDataTable
observeEvent
observeEvent(input$goButton,{
data$df <- somefunction()
})
output$exampleTable <- DT::renderDataTable({data$df})
用作reactiveValues
中间状态来保存变量,以便以后重用它们。
推荐阅读
- html - GET 请求不知从何而来
- python - 如何从excel文件创建多级数据框?
- c++ - 对象引用中的字段在不同的方法中返回不同的值
- sql - 查询记录 - 上传到 BigQuery 的 JSON 数据
- wpf - 除非与异步代码一起使用,否则 WPF 绑定不起作用
- netsuite - 在 Mule 4 中使用 Netsuite 连接器获取列表操作
- powershell - 将写入进度条添加到脚本 Powershell
- ios - 从 CMSampleBuffer 转换为 NSData 图像不超过 50MB 内存
- python - python中相同类型的类属性的最佳实践是什么?
- wordpress - 如何通过子页面一次性将所有请求重定向到 https 和 www