使用R的flextable包时,有没有办法将字符串的粗体部分传递给add_header_lines

问题描述

我正在使用我喜欢的flextable包为Word文档创建几个表。但是,在表格标题中加粗部分文本时遇到了一些麻烦。例如,我希望标题显示为“ 表1 ”。而不是“表1。我表标题的其余部分。”

found this documentation,经过反复试验,我终于得到了想要的结果。但是感觉可能有更直接的方法来获得它。这是我当前的解决方案:

library(dplyr)
library(flextable)

mtcars_ft <- flextable(head(mtcars)) %>% 
  # Add a blank title line to top of table
  add_header_lines("") %>% 
  # Use compose to bold "Table #."
  compose(
    i = 1,part = "header",value = as_paragraph(
      as_chunk("Table 1. ",props = fp_text(bold = TRUE)),"Here is my example mtcars ft."
    ),)

这是我的结果的屏幕截图:

enter image description here

解决方法

下面的解决方案既可以执行所需的操作,又可以在Word中使用自动编号,以便在更新后可以更新编号和引用。

library(officer)
library(flextable)

mtcars_ft <- flextable(head(mtcars)) %>% set_table_properties(layout = "autofit")

bold_face <- fp_text(bold = TRUE,font.size = 11)

fpar_ <- fpar(
  run_autonum(seq_id = 'tab',bkm = 'a_bkm',pre_label = "Table ",prop = bold_face),"Here is my example mtcars ft." )

read_docx() %>% 
  body_add_fpar(fpar_,style = "centered") %>% 
  body_add_flextable(mtcars_ft) %>% 
  print(target = "example.docx")

enter image description here

这基本上是flextable::set_caption的工作(但无法根据需要设置文本格式)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...