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

How to add multiple comments to excel workbook using openxlsx?

createComment openxlsx 函数描述指出注释可以是 "Character vector",因此应用于多个单元格。

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

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

我是不是漏掉了什么或者这是一个增强请求?

此 MWE 失败并显示以下消息:"Error in comment_list[[i]]$style[[j]] : subscript out of bounds"

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 中的示例应用多种样式。

可能解决此问题的最简单方法是使用 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)