如何在Shiny中显示htmlTable包生成的响应式表格?
Fixing htmlTable Display in Shiny
The issue you're hitting is that renderTable() and tableOutput() are built for converting standard data frames/tables into HTML automatically—they don't handle pre-generated HTML from the htmlTable package. To get your formatted table to display correctly, you need to use Shiny components designed to render raw HTML content.
Here's how to adjust your code:
Key Fixes
- UI Side: Swap
tableOutput("filetable")forhtmlOutput("filetable")—this output type is made to render HTML directly, not convert raw data into a table. - Server Side: Replace
renderTable({selectedData()})withrenderUI({selectedData()})—renderUI()handles custom HTML elements and will properly render the structured table fromhtmlTable().
Modified Full Code
library(shiny) library(htmlTable) #################### ui part ############################################## ui <- pageWithSidebar( headerPanel("Tables"), sidebarPanel( actionButton("goButton", "Run Table") ), mainPanel( htmlOutput("filetable") # Updated from tableOutput ) ) #################### server part ####################################### server <- function(input,output) { selectedData <- eventReactive(input$goButton, { # Create the table (using table from htmlTables doc as example) htmlTable(matrix(paste("Content", LETTERS[1:16]), ncol=4, byrow = TRUE), header = paste(c("1st", "2nd", "3rd", "4th"), "header"), rnames = paste(c("1st", "2nd", "3rd", "4th"), "row"), rgroup = c("Group A", "Group B"), n.rgroup = c(2,2), cgroup = c("Cgroup 1", "Cgroup 2†"), n.cgroup = c(2,2), caption="Basic table with both column spanners (groups) and row groups", tfoot="† A table footer commment") }) output$filetable <- renderUI({selectedData()}) # Updated from renderTable } shinyApp(ui,server)
Why This Works
htmlTable()returns an object of classhtmlTable, which is essentially structured HTML.renderUI()recognizes this format and passes it straight tohtmlOutput()to render as a styled table, instead of treating it like raw text.- The original
renderTable()was trying to parse your HTML string as if it were a data set, which is why you saw raw HTML code instead of the formatted table.
内容的提问来源于stack exchange,提问作者jrhartley
相关产品推荐
相关产品推荐

