【发布时间】:2021-12-30 20:09:45
【问题描述】:
我想对下面的代码做一些调整。请注意,当您运行应用程序时,我有radioButtons 有两个选项,Excel 和数据库。我的想法是,如果该人按下 Excel,则将出现 fileInput 供该人选择 Excel 文件,如果该人选择“数据库”选项,则将连接到数据库,因此,在第二种情况下,@987654323 @ 不会出现,它只会与数据库建立连接。会发生以下情况:
con <- DBI::dbConnect(odbc::odbc(),
Driver = "[your driver's name]",
Server = "[your server's path]",
Database = "[your database's name]",
UID = rstudioapi::askForPassword("Database user"),
PWD = rstudioapi::askForPassword("Database password"),
Port = 1433)
data <-tbl(con, in_schema("dbo", "date1")) %>%
collect()
data2 <- tbl(con, in_schema("dbo", "date2")) %>%
collect()
所以我想对下面的代码进行这些调整。
可执行代码如下:
library(shiny)
library(shinythemes)
library(readxl)
ui <- fluidPage(
shiny::navbarPage(theme = shinytheme("flatly"), collapsible = TRUE,
br(),
tabPanel("PAGE1",
sidebarLayout(
sidebarPanel(
radioButtons("button",
label = h3("Data source"),
choices = list("Excel" = "Excel", "Database" = "database"),
selected = "File"),
uiOutput('fileInput'),
),
mainPanel(
)))))
server <- function(input, output,session) {
data <- reactive({
if (is.null(input$file)) {
return(NULL)
}
else {
df3 <- read_excel(input$file$datapath,sheetnames()[1])
validate(need(all(c('date1', 'date2') %in% colnames(df3)), "Incorrect file"))
df4 <- df3 %>% mutate_if(~inherits(., what = "POSIXct"), as.Date)
return(df4)
}
})
data2 <- reactive({
req(input$file)
df1 <- read_excel(input$file$datapath,sheetnames()[2])
df1
})
output$fileInput <- renderUI({
fileInput("file",h4("Import file"), multiple = T, accept = ".xlsx")
})
sheetnames <- eventReactive(input$file, {
available_sheets = openxlsx::getSheetNames(input$file$datapath)
})
}
shinyApp(ui = ui, server = server)
【问题讨论】: