R语言DT包datatable渲染表格时如何将第4、8行设为粗体
问题描述
使用R语言DT包的datatable()函数渲染数据框为HTML交互表格时,需要将表格的第4行、第8行设置为粗体样式,现有基础实现代码如下:
df <- data.frame (origin = c("A","B","C","D","E","F","G","H","I","J"), Percentage = c(23,16,32,71,3,60,15,21,44,60), rate = c(10,12,20,200,-25,12,13,90,-105,23), change = c(10,12,-5,12,6,8,0.5,-2,5,-2)) library(DT) # 隐藏筛选栏清除按钮 datatable(df, options = list(autoWidth = TRUE, initComplete = JS(" function(settings, json) { $(this.api().table().header()).css({ 'font-size': '12px', }); } ")), filter = list( position = 'top', clear = FALSE ))%>% formatStyle(columns = colnames(.$x$data), `font-size` = "11px")
当前表格渲染效果:
实现方案
直接在现有样式设置的代码链后追加styleRow规则即可,styleRow的行索引从1开始计数,和R数据框原生行号一致,且样式会绑定对应数据行,排序、分页操作后不会出现行样式错位问题,修改后完整代码如下:
df <- data.frame (origin = c("A","B","C","D","E","F","G","H","I","J"), Percentage = c(23,16,32,71,3,60,15,21,44,60), rate = c(10,12,20,200,-25,12,13,90,-105,23), change = c(10,12,-5,12,6,8,0.5,-2,5,-2)) library(DT) datatable(df, options = list(autoWidth = TRUE, initComplete = JS(" function(settings, json) { $(this.api().table().header()).css({ 'font-size': '12px', }); } ")), filter = list( position = 'top', clear = FALSE ))%>% formatStyle(columns = colnames(.$x$data), `font-size` = "11px") %>% # 新增:设置第4、8行粗体 formatStyle( columns = colnames(df), fontWeight = styleRow(rows = c(4, 8), values = rep("bold", 2)) )
如果后续需要根据单元格值动态设置行样式,把
styleRow替换为styleEqual写判断逻辑即可,固定行号的场景下上述写法是最简洁、兼容性最好的方案。
内容的提问来源于stack exchange,提问作者user18948933
相关产品推荐
相关产品推荐

