首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >openxlsx中的换行符

openxlsx中的换行符
EN

Stack Overflow用户
提问于 2020-04-27 16:16:52
回答 1查看 1.1K关注 0票数 3

关于R中的openxlsx库的一个问题:

我正在寻找一种在openxlsx中向单元格值添加换行符的方法,以便该值在Excel中显示在两行(或更多行)中。我的意思是,通过键入一个值,按Alt-Enter并添加另一个值,可以在Excel中获得类似的功能。

不,我不是在寻找一种技巧来做这件事,使用数据框或具有适当列宽的文字换行,而是其他东西。

例如,这个候选解决方案不起作用:

代码语言:javascript
运行
复制
openxlsx::write.xlsx(
    data.frame("I want this in two lines\nin one cell"),
    stringsAsFactors = FALSE,
    file = "foo.xlsx"
)

所有内容仍然打印在一行上。

EN

回答 1

Stack Overflow用户

发布于 2020-05-06 15:00:24

试试这个:

excel中做这么简单的事情似乎有很多工作要做,但我发现使用openxlsx你可以很轻松地完成大多数事情,我真的很喜欢这个包。

代码语言:javascript
运行
复制
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)

这会导致:

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61454433

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档