我正在编写一个脚本来使用 呈现 Excel 输出openxlsx
,但在单元格内换行文本时遇到了困难。
我的输出中有一张“报告说明”表,其中包含有关文件中分析的常见免责声明,该免责声明由写入变量的文本字符串填充。我必须在单独的工作表中执行此操作,因为所需的免责声明文本太长,无法包含在分析表的页眉或页脚中。问题是文本字符串不会在单元格中换行,这会产生可读性问题。我尝试了各种方法来强制执行此操作,但都没有成功。
#### Example Data ####
library(tidyverse)
library(openxlsx)
library(openxlsx2)
reportnotes<- "THIS IS AN EXAMPLE TEXT STRING THAT I WANT TO WRITE TO AN EXCEL DOCUMENT. HOPEFULLY IT'S LONG ENOUGH TO MAKE MY POINT."
output<-createWorkbook()
addWorksheet(output, "Report Notes")
writeData(output, "Report Notes", reportnotes,
startCol = 1,
startRow = 1,
colNames = TRUE,
rowNames = FALSE,
keepNA = TRUE)
pageSetup(output, "Report Notes", orientation = "landscape", scale = 100, fitToWidth = TRUE)
我尝试了以下解决方案:
#### Attempted Solutions ####
# Solution 1) Using str_wrap() and setColWidths() and setRowHeights() to create the wrap.
# Resulted in an adjusted column and row height but no wrapped text:
reportnotes<-reportnotes%>%
str_wrap(width = 80, indent = 0, whitespace_only = FALSE)
setColWidths(output, "Report Notes", cols = 1, widths=70)
setRowHeights(output, "Report Notes", rows = 1, heights = 150)
# Solution 2) Defining a cell style. This solution produced an error:
wb_add_cell_style(output, sheet="Report Notes", dims = "A1", apply_border = TRUE, wrap_text=TRUE)
# Error: wb must be class wbWorkbook or R6
我的控制台是RStudio 2023.06.1+524 "Mountain Hydrangea" Release (547dcf861cac0253a8abb52c135e44e02ba407a1, 2023-07-07) for windows
,我的 R 版本是R version 4.3.0 (2023-04-21 ucrt) -- "Already Tomorrow"
。由于组织政策,我对更新版本的访问受到限制。
鉴于这些限制,我该怎么做才能强制文本在 Excel 输出中换行?
不确定是否
openxlsx2
会引起冲突,但openxlsx
您可以创建一种样式,然后将其应用于感兴趣的单元格。例如: