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

R formattable包生成表格如何调整行高 导出PDF时减小行间距

解决方案

行间距过大的核心原因是formattable生成的HTML表格默认给单元格设置了较高的内边距与行高,直接添加自定义CSS覆盖默认样式即可解决,具体修改如下:

  1. 在生成FT对象后、调用export_formattable前,插入一段自定义样式代码,强制修改表格单元格的内边距和行高
  2. 可通过调整CSS参数自定义紧凑程度,上下内边距设为0即可实现内容完全贴合行分隔线的效果

完整修改后代码

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)
      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; border-collapse: collapse;"')

# 新增:添加自定义CSS控制行高
FT <- htmlwidgets::prependContent(FT,
  tags$style("
    .formattable_widget td, .formattable_widget th {
      padding: 0 4px !important; /* 第一个值为上下内边距,设为0即可完全贴合分隔线 */
      line-height: 1 !important; /* 行高系数,数值越小越紧凑 */
    }
  ")
)

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

参数调整说明

  • padding: 0 4px:第一个参数控制单元格上下留白,第二个参数控制左右留白,可根据需求调整数值
  • line-height: 1:行高和字体高度的比例,设为1时行高刚好等于当前字体高度
  • 原代码中注释的Name字段加粗不生效的问题也会同步解决,新增的全局样式没有覆盖字体加粗规则

内容的提问来源于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 01:54:05