如何在文件更改时更新用户界面 [英] How to update UI on file change

查看:0
本文介绍了如何在文件更改时更新用户界面的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在使用几个Excel文件构建一个shinydashboard。

我在框的页脚中插入了指向这些文件的链接,我想在更改Excel文件中的内容时刷新shinydashboard。 我不想每次都运行整个R代码。

文件内容更改后如何重新呈现输出?

这里有一个例子:

sidebar <- dashboardSidebar(
sidebarMenu( menuItem("Hello", tabName = "Hello", icon = icon("dashboard"))
          ))

body <- dashboardBody(
 tabItems(

tabItem(tabName = "Hello",


        box(title = "my file", 
            footer = a("df.xlsx", href="df.xlsx" ) ,
            DT::dataTableOutput("df1"),style = "font-size: 100%; overflow: auto;",
            width = 12, hight = NULL, solidHeader = TRUE, collapsible = TRUE, collapsed = TRUE, status = "primary")
)))


ui <- dashboardPage(
 dashboardHeader(title = "My Dashboard"),
 sidebar,
body)


server <- function(input, output) {
  output$df1 <- renderDataTable({ 
df <- read_excel("df.xlsx")
DT::datatable(df, escape = FALSE, rownames=FALSE,class = "cell-border",
              options =list(bSort = FALSE, paging = FALSE, info = FALSE)
  )
  })
}



shinyApp(ui, server)

推荐答案

要监视文件中的更改,可以使用文件的校验和,如下所示:

library(shiny)
library(digest)

# Create data to read
write.csv(file="~/iris.csv",iris)

shinyApp(ui=shinyUI(
  fluidPage(
    sidebarLayout(
      sidebarPanel(
        textInput("path","Enter path: "),
        actionButton("readFile","Read File"),
        tags$hr()
      ),
      mainPanel(
        tableOutput('contents')
      )))
),
server = shinyServer(function(input,output,session){
  file <- reactiveValues(path=NULL,md5=NULL,rendered=FALSE)

  # Read file once button is pressed
  observeEvent(input$readFile,{
    if ( !file.exists(input$path) ){
      print("No such file")
      return(NULL)
    }
    tryCatch({
      read.csv(input$path)
      file$path <- input$path
      file$md5  <- digest(file$path,algo="md5",file=TRUE)
      file$rendered <- FALSE
    },
    error = function(e) print(paste0('Error: ',e)) )
  })

  observe({
    invalidateLater(1000,session)
    print('check')

    if (is.null(file$path)) return(NULL)

    f   <- read.csv(file$path)
    # Calculate ckeksum
    md5 <- digest(file$path,algo="md5",file=TRUE)

    # If no change in cheksum, do nothing
    if (file$md5 == md5 && file$rendered == TRUE) return(NULL)

    output$contents <- renderTable({

      print('render')
      file$rendered <- TRUE
      f
    })
  })

}))

这篇关于如何在文件更改时更新用户界面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆