You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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") for htmlOutput("filetable")—this output type is made to render HTML directly, not convert raw data into a table.
  • Server Side: Replace renderTable({selectedData()}) with renderUI({selectedData()})—renderUI() handles custom HTML elements and will properly render the structured table from htmlTable().

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&dagger;"),
              n.cgroup = c(2,2),
              caption="Basic table with both column spanners (groups) and row groups",
              tfoot="&dagger; A table footer commment")
  })
  output$filetable <- renderUI({selectedData()})  # Updated from renderTable
}

shinyApp(ui,server)

Why This Works

  • htmlTable() returns an object of class htmlTable, which is essentially structured HTML. renderUI() recognizes this format and passes it straight to htmlOutput() 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:38:56