关于R中的openxlsx库的一个问题:
我正在寻找一种在openxlsx中向单元格值添加换行符的方法,以便该值在Excel中显示在两行(或更多行)中。我的意思是,通过键入一个值,按Alt-Enter并添加另一个值,可以在Excel中获得类似的功能。
不,我不是在寻找一种技巧来做这件事,使用数据框或具有适当列宽的文字换行,而是其他东西。
例如,这个候选解决方案不起作用:
openxlsx::write.xlsx(
data.frame("I want this in two lines\nin one cell"),
stringsAsFactors = FALSE,
file = "foo.xlsx"
)所有内容仍然打印在一行上。
发布于 2020-05-06 15:00:24
试试这个:
在excel中做这么简单的事情似乎有很多工作要做,但我发现使用openxlsx你可以很轻松地完成大多数事情,我真的很喜欢这个包。
txt <- data.frame(t = c("I want this in two lines", "in one cell"), stringsAsFactors = FALSE)
wb <- createWorkbook()
addWorksheet(wb, "Sheet 1")
writeData(wb, "Sheet 1", x = txt)
# to make sure your text shows as two lines
setRowHeights(wb, "Sheet 1", rows = 4, height = 30)
# this seems to force the line break to split the text over two lines
style1 <- createStyle(wrapText = TRUE)
addStyle(wb, sheet = 1, style1, rows = 4, cols = 1, gridExpand = TRUE)
#narrow width produces multiple lines as a consequence of text wrap
setColWidths(wb, sheet = 1, cols = 1, widths = 40)
#Here's the key bit; excel does not seem to like \n as a line break an online search suggested CHAR(10) as the alternative to `alt enter` keystroke for line break in an excel cell
writeFormula(wb, 1, x = "A2&CHAR(10)&A3", startCol = 1, startRow = 4)
saveWorkbook(wb, file = "foo.xlsx", overwrite = TRUE)这会导致:

https://stackoverflow.com/questions/61454433
复制相似问题