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

在Shiny R的DT table中如何用formatStyle将第一行设为粗体

DT表格第一行设置粗体的实现方法

你提供的参考代码已经可以直接实现基础需求,相关配置说明如下:

  • formatStyle第一个参数传入0,配合target = "row"配置,指定对DT行索引为0的行(即表格第一行,DT的行/列索引默认从0开始计数)应用样式
  • fontWeight = 'bold'参数明确指定字体为粗体
  • 默认分页场景下,上述写法是设置当前展示分页的第一行为粗体;如果需要设置整个数据集的第一行(分页跳转后始终保持原数据集第一行是粗体),可以用行值匹配的方式实现

完整使用示例

单独使用DT场景

library(DT)
datatable(iris, options = list(pageLength = 5)) %>%
  formatStyle(0, target = "row", fontWeight = 'bold')

Shiny中嵌入使用场景

library(DT)
library(shiny)

ui <- fluidPage(
  DTOutput("iris_table")
)

server <- function(input, output) {
  output$iris_table <- renderDT({
    datatable(iris, options = list(pageLength = 5)) %>%
      formatStyle(0, target = "row", fontWeight = 'bold')
  })
}

shinyApp(ui, server)

固定全数据集第一行粗体的实现

datatable(iris, options = list(pageLength = 5)) %>%
  formatStyle("Sepal.Length", target = "row", 
              fontWeight = styleEqual(iris$Sepal.Length[1], "bold"))

额外补充:表头行设置粗体

DT默认表头已经是粗体样式,你也可以通过initComplete配置强制指定:

datatable(iris, options = list(pageLength = 5,
  initComplete = JS(
    "function(settings, json) {",
    "$(this.api().table().header()).css({'font-weight': 'bold'});",
    "}"
  )))

内容的提问来源于stack exchange,提问作者IvanM

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 03:15:08