Home » excel » r – Read and write excel file with comments

r – Read and write excel file with comments

Posted by: admin May 14, 2020 Leave a comment

Questions:

Q. Im looking for a way to preserve comments of an excel file after reading and manipulating.

0. My excelfile: (cant share it with you!)

enter image description here

1. I want to read it like that: (having the col comment in excel as col comment in R)

(with whatever library that does it. openxlsx would be best)

df<- data.frame(a=1:3,b=4:6,c=7:9)
comment(df$a) <- "Random comment" #is there a better practice to preserve the excel comment?

2. Random manipulation of the data:

df[2:3] <- df[2:3] * 2
df$d    <- "funny"

3. Save the data (it should look like this:)
enter image description here

Edit:

library(openxlsx)

wb <- loadWorkbook("commented.xlsx")
df <- readWorkbook(wb)

df[2:3] <- df[2:3] * 2
df$d    <- "funny"
df <- rev(df)
df <- df[order(df$a,decreasing = T),]

writeData(wb, 1, df)
saveWorkbook(wb, "modified.xlsx")

A wonderful solution so far!

  1. The comments stay stationary as seen by this little example.
  2. I̶ ̶g̶e̶t̶ ̶a̶n̶ ̶a̶d̶d̶i̶t̶i̶o̶n̶a̶l̶ ̶e̶m̶p̶t̶y̶ ̶”̶c̶o̶m̶m̶e̶n̶t̶ ̶p̶o̶p̶ ̶u̶p̶ ̶w̶i̶n̶d̶o̶w̶”̶ ̶i̶n̶ ̶m̶y̶ ̶r̶e̶s̶u̶l̶t̶i̶n̶g̶ ̶f̶i̶l̶e̶.̶ ̶I̶s̶ ̶i̶t̶ ̶j̶u̶s̶t̶ ̶m̶e̶?̶ (workaround available!)
How to&Answers:

You can do this with openxlsx: use loadWorkbook() to read in the original file, modify the data that you want, and finish up with saveWorkbook(). The comments will be preserved:

library(openxlsx)

wb <- loadWorkbook("commented.xlsx")
df <- readWorkbook(wb)

df[2:3] <- df[2:3] * 2
df$d    <- "funny"

writeData(wb, 1, df)
saveWorkbook(wb, "modified.xlsx")

unlink(c("commented.xlsx", "modified.xlsx"))

Sample data:

library(openxlsx)

wb <- createWorkbook("unknown")
addWorksheet(wb, "Sheet 1")

df <- data.frame(a = 1:3, b = 4:6, c = 7:9)
writeData(wb, 1, df)

comment <- createComment("Random comment")
writeComment(wb, 1, 1, 1, comment)

saveWorkbook(wb, "commented.xlsx")