如何在Shiny应用中设置表格每页仅显示5行并调整表格背景样式
解决方案
实现说明
- 控制表格每页行数:在
renderDataTable的options参数中配置pageLength = 5即可实现每页固定展示5条数据 - 消除交替行透明背景:首先关闭表格自带的斑马纹样式(设置
striped = FALSE),同时添加自定义CSS强制所有表格行背景为纯白色,避免页面渐变背景透上来
完整修改后代码
library(shiny) library(dplyr) # alternatively, this also loads %>% library(shinyWidgets) regex_to_apply <- "\bMASTER DATA\b|\bSOURCE LIST\b|\bVALIDITY DATES\b|\bMRP CONTROLLER\b|\bPSV\b|\bELIGIBILITY\b|\bCOST\b|\bMARKETING EXCLUSION\b|\bEFFECTIVITY\b|\bMISSING\b|bBLANK\b" ui <- fluidPage( # 新增自定义CSS强制表格行背景为纯白 tags$style(HTML(" table.dataTable tbody tr { background-color: #ffffff !important; } ")), # use a gradient in background, setting background color to blue setBackgroundColor( color = c("#F7FBFF", "#2171B5"), gradient = "radial", direction = c("top", "left") ), sidebarLayout( sidebarPanel( fileInput("file1", "Choose CSV File", accept = c( "text/csv", "text/comma-separated-values,text/plain", ".csv") ), tags$hr(), checkboxInput("header", "Header", TRUE), # Button downloadButton("downloadData", "Download"), actionButton('apply_regex', 'Apply Regex') ), mainPanel( dataTableOutput("contents") ) ) ) server <- function(input, output) { rv <- reactiveValues() observe({ req(input$file1) # input$file1 will be NULL initially. After the user selects # and uploads a file, it will be a data frame with 'name', # 'size', 'type', and 'datapath' columns. The 'datapath' # column will contain the local filenames where the data can # be found. inFile <- input$file1 if (is.null(inFile)) return(NULL) rv$data <- read.csv(inFile$datapath, header = input$header, encoding = "UTF-8") }) output$contents <- renderDataTable({ rv$data }, # 配置分页行数、关闭斑马纹 options = list(pageLength = 5), striped = FALSE ) output$downloadData <- downloadHandler( filename = function() { paste("myfile",Sys.Date(), ".csv", sep = "") }, content = function(file) { write.csv(rv$data, file, row.names = FALSE) } ) observeEvent(input$apply_regex, { rv$data <- rv$data %>% mutate(close_notes = close_notes %>% as.character() %>% toupper()) %>% filter(grepl(regex_to_apply, close_notes)) }) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者Jasmine Dogu
相关产品推荐
相关产品推荐

