繁体   English   中英

如何使用 openxlsx 向 excel 工作簿添加多条评论?

[英]How to add multiple comments to excel workbook using openxlsx?

createComment openxlsx function 描述指出注释可以是“字符向量”,因此适用于多个单元格。

但是,添加评论似乎仅限于一个单元格。

有没有办法使用字符向量向一系列单元格添加多个注释?

我错过了什么还是这是一个增强请求?

此 MWE 失败并显示以下消息:“comment_list[[i]]$style[[j]] 中的错误:下标超出范围”

library(openxlsx)

x <- as.data.frame(matrix(1:12, nrow = 3))
names(x) <- letters[1:4]

comment_vector <- paste("Comment", 1:4)

wb <- createWorkbook()
addWorksheet(wb, 1)

header_comments <- createComment(comment = comment_vector)
writeComment(wb, 1, col = 1:4, row = 1, comment = header_comments)

writeData(wb, sheet = 1, startRow = 1, x)

saveWorkbook(wb, "muliple_comments.xlsx", overwrite = TRUE)

这行得通,但必须有更好的方法......


header1_comment <- createComment(comment = comment_vector[1])
writeComment(wb, 1, col = 1, row = 1, comment = header1_comment)

header2_comment <- createComment(comment = comment_vector[2])
writeComment(wb, 1, col = 2, row = 1, comment = header2_comment)

header3_comment <- createComment(comment = comment_vector[3])
writeComment(wb, 1, col = 3, row = 1, comment = header3_comment)

header4_comment <- createComment(comment = comment_vector[4])
writeComment(wb, 1, col = 4, row = 1, comment = header4_comment)

writeData(wb, sheet = 1, startRow = 1, x)

saveWorkbook(wb, "05_muliple_comments.xlsx", overwrite = TRUE)

生产: 在此处输入图像描述

我不认为createComment允许在多个单元格中进行评论,字符向量组件可以按照?createComment中的示例应用多个 styles 。

解决这个问题的最简单方法可能是使用lapplyfor循环。

lapply(1:4, FUN = function(x) writeComment(wb, 1, col = x, row = 1, comment = createComment(comment = comment_vector[x])))

因此,在您提供的示例中,它将类似于:

library(openxlsx)

x <- as.data.frame(matrix(1:12, nrow = 3))
names(x) <- letters[1:4]
comment_vector <- paste("Comment", 1:4)

wb <- createWorkbook()
addWorksheet(wb, 1)

# Add multiple comments
lapply(1:4, FUN = function(x) writeComment(wb, 1, col = x, row = 1, comment = createComment(comment = comment_vector[x])))

writeData(wb, sheet = 1, startRow = 1, x)
saveWorkbook(wb, "muliple_comments.xlsx", overwrite = TRUE)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM