【问题标题】:How to add multiple comments to excel workbook using openxlsx?如何使用 openxlsx 向 Excel 工作簿添加多个注释?
【发布时间】:2020-04-06 10:30:28
【问题描述】:

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

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

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

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

此 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)

制作:

【问题讨论】:

    标签: r openxlsx


    【解决方案1】:

    我不认为createComment 允许 cmets 在多个单元格中,字符向量组件可以按照?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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-28
      • 2018-04-23
      • 2016-03-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多