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

flextable中根据数值条件设置红色加粗字体的实现方法

flextable 按条件设置单元格样式解决方案

核心逻辑是使用flextable自带的bold()和color()函数指定行筛选条件,即可实现需求,修改后的可运行代码如下:

# 需提前加载依赖包
library(flextable)
library(officer)

# 注意Windows路径在R中建议用正斜杠/双反斜杠,避免转义字符报错
file_path <- "c:/temp/test_table.docx"

df <- data.frame(
    InstanceName = c("Instance1", "Instance2", "Instance3", "Instance4", "Instance5"),
    Value = c(15, 5, 11, 0, 5)
)

table_to_save <- flextable(df) %>%
  # 给Value列中数值大于10的行设置加粗样式
  bold(i = ~ Value > 10, j = "Value", bold = TRUE) %>%
  # 给相同条件的单元格设置红色字体
  color(i = ~ Value > 10, j = "Value", color = "red")

save_as_docx(
    table_to_save,
    path =  file.path(file_path)
)

参数说明:

  • i参数用于指定要设置样式的行,支持公式形式的条件筛选,~ Value >10就代表筛选Value列数值大于10的所有行
  • j参数用于指定要设置样式的列,这里直接指定列名Value,仅修改该列符合条件的单元格样式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:15:05