R flextable合并单元格换行设置/移除及表头合并配置
在flextable中解决旋转文本拉伸与表头合并问题
问题说明
运行以下R代码时,会遇到两个问题:
- 第1、2列的旋转文本出现不必要的自动换行,无法拉伸至合并单元格的整个高度
- 表头左上角的四个单元格需要合并并清空内容
原代码:
library(dplyr) library(flextable) tibble(Ind1 = rep("Indicator name 1", 3), ranges1 = c("[0; 1)", "[1; 2)", "[2; 3)"), `[0; 1.5)` = c("Text11\na\nb\nc\nd\ne", "Text21\na\nb\nc\nd\ne", "Text31\na\nb\nc\nd\ne"), `[1,5; 3)` = c("Text12\na\nb\nc\nd\ne", "Text22\na\nb\nc\nd\ne", "Text32\na\nb\nc\nd\ne"), `[3; 4.5)` = c("Text13\na\nb\nc\nd\ne", "Text23\na\nb\nc\nd\ne", "Text33\na\nb\nc\nd\ne")) %>% flextable() %>% flextable::theme_box() %>% flextable::bold(j = c(1, 2)) %>% flextable::rotate(j = c(1, 2), rotation = "btlr") %>% merge_v(j = 1) %>% flextable::add_header_row(colwidths = c(1, 1, 3), values = c("", "", "Indicator name\n2"))
解决方案
1. 让旋转文本拉伸至合并单元格范围
旋转文本时设置对齐方式,同时调整行高为旋转文本预留足够空间,避免自动换行;合并单元格后修复边框问题。
2. 合并表头左上角单元格并清空内容
先清空指定表头单元格的内容,再合并表头的2行2列区域。
整合后的完整代码:
library(dplyr) library(flextable) tibble(Ind1 = rep("Indicator name 1", 3), ranges1 = c("[0; 1)", "[1; 2)", "[2; 3)"), `[0; 1.5)` = c("Text11\na\nb\nc\nd\ne", "Text21\na\nb\nc\nd\ne", "Text31\na\nb\nc\nd\ne"), `[1,5; 3)` = c("Text12\na\nb\nc\nd\ne", "Text22\na\nb\nc\nd\ne", "Text32\na\nb\nc\nd\ne"), `[3; 4.5)` = c("Text13\na\nb\nc\nd\ne", "Text23\na\nb\nc\nd\ne", "Text33\na\nb\nc\nd\ne")) %>% flextable() %>% theme_box() %>% bold(j = c(1, 2)) %>% # 旋转文本并设置居中对齐,避免自动换行 rotate(j = c(1, 2), rotation = "btlr", align = "center", valign = "middle") %>% merge_v(j = 1) %>% add_header_row(colwidths = c(1, 1, 3), values = c("", "", "Indicator name\n2")) %>% # 清空表头第2行的1、2列内容 mk_par(i = 2, j = c(1, 2), value = as_paragraph(""), part = "header") %>% # 合并表头左上角的2行2列区域 merge_at(i = c(1, 2), j = c(1, 2), part = "header") %>% # 调整行高适配旋转文本 height_all(height = 1.2) %>% # 修复合并后的边框问题 fix_border_issues()
关键说明
rotate()的align和valign参数确保旋转文本在单元格内居中,避免因对齐偏差导致的换行height_all()设置统一行高,为旋转文本提供足够展示空间merge_at()配合mk_par()实现表头左上角空白合并单元格的效果
内容的提问来源于stack exchange,提问作者asd-tm
相关产品推荐
相关产品推荐

