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

如何调整R语言中formattable导出表格的行间距与图片宽高比

解决方案

你之前调整的参数未生效是因为表格行间距由HTML表格的CSS样式控制,不属于你修改的几个参数的控制范围,按以下方式修改代码即可实现需求:

修改后的完整可运行代码

library(formattable)
library(htmltools)
library(webshot2)

df <- data.frame(
  id = 1:10,
  name = c("Bob", "Ashley", "James", "David", "Jenny", 
           "Hans", "Leo", "John", "Emily", "Lee"), 
  age = c(28, 27, 30, 28, 29, 29, 27, 27, 31, 30),
  grade = c("C", "A", "A", "C", "B", "B", "B", "A", "C", "C"),
  Test.number.1.score = c(8.9, 9.5, 9.6, 8.9, 9.1, 9.3, 9.3, 9.9, 8.5, 8.6),
  test2_score = c(9.1, 9.1, 9.2, 9.1, 8.9, 8.5, 9.9, 9.3, 9.1, 8.6),
  final_score = c(9, 9.3, 9.4, 9, 9, 8.9, 9.25, 9.6, 8.8, 8.7),
  registered = c(TRUE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE, FALSE, FALSE, FALSE),
  stringsAsFactors = FALSE)

# 新增样式配置,调整行间距
dt <- formattable(df,
  # 给单元格设置行高和上下内边距,增大行间距
  list(`td` = formatter("td", style = ~ style("line-height" = "2.5em", "padding-top" = "10px", "padding-bottom" = "10px"))),
  # 设置表格整体样式,可选,让内容更宽松
  table.attr = "style='border-collapse: collapse; width: 100%;'"
)

export_formattable <- function(f, file, 
                               width = "100%", height = "1200px", # 把原来的16px改大,适配调整后的表格高度
                               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,
              vwidth = 600, vheight = 1600, # 调整视口宽高,确保高度大于宽度
              file = file,
              selector = ".formattable_widget",
              delay = delay)
}
export_formattable(dt,'./data.png')

核心修改点说明

  • 生成formattable对象时通过formatter给所有td单元格设置行高、上下内边距,直接增大行间距,数值可以根据自己需要的宽松程度调整
  • 调大导出函数的height参数,匹配调整后变大的表格高度
  • 缩小webshot的vwidth、增大vheight,确保最终导出的图片高度大于宽度

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 03:45:03