Shiny应用问题:文件上传后表格渲染与下载功能失效
Fixing Your Shiny App: Table Rendering & Download Issues
Let's break down the issues in your code and fix them step by step. The core problem is indeed missing reactive logic—your company_data isn't set up to react to changes in user inputs, plus there are a few small syntax/usage errors blocking functionality.
Key Fixes Needed:
- Wrap filtered data in a reactive expression: This ensures the data updates automatically when the user uploads a new file or modifies the text inputs.
- Correct data frame column naming: When converting the text lines to a data frame, you need to explicitly name the column so
str_detectknows what to filter. - Fix download handler logic: The download handler can't directly access
company_data(it's not in scope); you need to call the reactive variable instead, plus correct thewrite.csvparameters.
Full Corrected Code:
library(shiny) library(tidyverse) ui <- fluidPage( titlePanel("Download data"), sidebarLayout( sidebarPanel( fileInput("file1", "Choose .txt file", multiple = F, accept = c(".txt")), textInput('energy_co', 'Name of energy company'), textInput('asset', 'name of Asset Manager'), downloadButton("downloadData", "Download") ), mainPanel( tableOutput("table") ) ) ) server <- function(input, output, session) { options(shiny.maxRequestSize=30*1024^2) # Reactive expression to handle data filtering filtered_data <- reactive({ req(input$file1, input$energy_co, input$asset) # Wait for all inputs to be present data <- read_lines(input$file1$datapath) text_df <- tibble(terms = data) # Explicitly name the column text_df %>% filter(str_detect(terms, input$asset)) %>% filter(str_detect(terms, input$energy_co)) %>% distinct(.) }) # Render table using the reactive data output$table <- renderTable({ filtered_data() }) # Fix download handler to use reactive data output$downloadData <- downloadHandler( filename = function() { paste("filtered_results_", Sys.Date(), ".csv", sep = "") # More meaningful filename }, content = function(file) { write.csv(filtered_data(), file, row.names = FALSE) } ) } shinyApp(ui, server)
What Changed:
- Reactive
filtered_data: This wraps all the data reading and filtering logic. Thereq()function ensures the code only runs once the user has uploaded a file and entered both search terms—prevents errors from missing inputs. - Column Naming:
tibble(terms = data)creates a data frame with a column namedterms, which matches what you're using instr_detect. - Download Handler:
- We call
filtered_data()inside the download handler to access the latest filtered data. - Fixed the
write.csvparameter (was usingfile1instead of the correctfileargument). - Updated the filename to be more descriptive and include the current date.
- We call
Now when you upload a TXT file, enter both terms, the table will render automatically, and the download button will export the filtered results correctly.
内容的提问来源于stack exchange,提问作者alex_stephenson
相关产品推荐
相关产品推荐

