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

R语言formattable包实现表格隔行浅灰斑马纹效果方法咨询

问题:R语言formattable包生成表格实现斑马纹效果

需求

  • 为formattable生成的表格添加类似kableExtra的斑马纹样式:奇数行填充浅灰色阴影,偶数行无填充
  • 最终表格需要导出后插入PDF文档
  • 此前直接修改td、tr元素样式会出现单元格阴影异常,自定义的单元格加粗格式也无法在导出文件中生效

原有实现代码

library("htmltools")
library("webshot")  
library(formattable)
DF <- data.frame(Ticker=c("", "", "", "IBM", "AAPL", "MSFT"),
                 Name=c("Dow Jones", "S&P 500", "Technology", 
                        "IBM", "Apple", "Microsoft"),
                 Value=accounting(c(15988.08, 1880.33, 50, 
                                    130.00, 97.05, 50.99)),
                 Change=percent(c(-0.0239, -0.0216, 0.021, 
                                  -0.0219, -0.0248, -0.0399)))

################################## FUNCTIONS ##################################
unit.scale = function(x) (x - min(x)) / (max(x) - min(x))
export_formattable <- function(f, file, width = "100%", height = NULL, 
                               background = "white", delay = 0.2)
    {
      w <- as.htmlwidget(f, width = width, height = height)
      #Remove row height!
      w <- htmlwidgets::prependContent(w, tags$style("td { padding: 0px  !Important;}"))
      path <- html_print(w, background = background, viewer = NULL)
      url <- paste0("file:///", gsub("\\\\", "/", normalizePath(path)))
      webshot(url,
              file = file,
              selector = ".formattable_widget",
              delay = delay)
    }
###############################################################################

FT <- formattable(DF, align =c("l","c","r","c"), list(
  Name=formatter("span", 
                 style = x ~ ifelse(x == "Technology", style(font.weight = "bold"), NA)),
  Value = color_bar("orange" , fun = unit.scale
                    ),
  Change = formatter("span", 
                     style = x ~ style(color = ifelse(x < 0 , "red", "green"), "font.size" = "18px"), 
                     x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)
                     )),
  table.attr = 'style="font-size: 18px; font-family: Calibri";')

FT
# 导出表格
export_formattable(FT,"/outputpath/FT.png")

解决方案

问题核心原因是CSS样式优先级不足,行背景样式被单元格默认样式、color_bar等内置格式的背景覆盖,同时自定义的加粗样式优先级不够导致导出后不生效。

修改步骤

  1. 调整export_formattable函数中注入的CSS规则,新增奇数行背景样式,同时设置所有单元格背景为透明,避免覆盖行级斑马纹
  2. 新增样式规则保证自定义的加粗格式正常生效

修改后完整代码

library("htmltools")
library("webshot")  
library(formattable)
DF <- data.frame(Ticker=c("", "", "", "IBM", "AAPL", "MSFT"),
                 Name=c("Dow Jones", "S&P 500", "Technology", 
                        "IBM", "Apple", "Microsoft"),
                 Value=accounting(c(15988.08, 1880.33, 50, 
                                    130.00, 97.05, 50.99)),
                 Change=percent(c(-0.0239, -0.0216, 0.021, 
                                  -0.0219, -0.0248, -0.0399)))

################################## FUNCTIONS ##################################
unit.scale = function(x) (x - min(x)) / (max(x) - min(x))
export_formattable <- function(f, file, width = "100%", height = NULL, 
                               background = "white", delay = 0.2)
    {
      w <- as.htmlwidget(f, width = width, height = height)
      # 新增斑马纹样式、单元格透明规则,修复自定义样式不生效问题
      w <- htmlwidgets::prependContent(w, tags$style("
        tr:nth-child(odd) {background-color: #f2f2f2 !important;}
        td { background: transparent !important; padding: 0px !important;}
        span[style*='font-weight: bold'] {font-weight: bold !important;}
      "))
      path <- html_print(w, background = background, viewer = NULL)
      url <- paste0("file:///", gsub("\\\\", "/", normalizePath(path)))
      webshot(url,
              file = file,
              selector = ".formattable_widget",
              delay = delay)
    }
###############################################################################

FT <- formattable(DF, align =c("l","c","r","c"), list(
  Name=formatter("span", 
                 style = x ~ ifelse(x == "Technology", style(font.weight = "bold"), NA)),
  Value = color_bar("orange" , fun = unit.scale
                    ),
  Change = formatter("span", 
                     style = x ~ style(color = ifelse(x < 0 , "red", "green"), "font.size" = "18px"), 
                     x ~ icontext(ifelse(x < 0, "arrow-down", "arrow-up"), x)
                     )),
  table.attr = 'style="font-size: 18px; font-family: Calibri";')

FT
# 导出表格
export_formattable(FT,"/outputpath/FT.png")

修改后导出的图片就会带有正常的斑马纹效果,直接插入PDF即可使用,如果需要调整灰色深浅,只需要修改#f2f2f2为对应的色值即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 02:45:02