Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to fill color while write to excel

I have a df like the one on the left. I would like to export it to an excel file with some formatting based on the Name value. What should I do? the rows filled with grey color every other unique names.

enter image description here

df<-structure(list(Name = c("Tom", "Tom", "Tom", "Jerry", "Jerry", 
"Amy", "Amy", "Amy", "Amy", "Ema", "Ema", "Ema"), Subject = c("PE", 
"ART", "ELA", "ELA", "MATH", "ELA", "MATH", "ART", "PE", "ART", 
"MATH", "ELA"), Score = c(98, 86, 75, 88, 100, 90, 86, 95, 78, 
88, 68, 95)), row.names = c(NA, -12L), class = c("tbl_df", "tbl", 
"data.frame"))

wb <- createWorkbook()
addWorksheet(wb, sheetName = "TEST")
writeData(wb, sheet = "TEST", x = df, startRow = 1)
saveWorkbook(wb, "test.xlsx", overwrite = TRUE)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could conditionally add a fill color using addStyle. Note that to do so we have to loop over the rows or the column to which the style should be applied:

library(openxlsx)
wb <- createWorkbook()
addWorksheet(wb, sheetName = "TEST")
writeData(wb, sheet = "TEST", x = df, startRow = 1)
rows <- which(df$Name %in% c("Jerry", "Ema"))
style <- createStyle(
  fgFill = "grey85"
)
for (col in 1:3) addStyle(wb, "TEST", rows = rows + 1, cols = col, style = style)
saveWorkbook(wb, "test.xlsx", overwrite = TRUE)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading