how to write in xlsx and modifying the format of the cells

875 views Asked by At

After running this code

library(XLConnect)

template <- loadWorkbook ( filename = "template.xlsx" , create = T )
createSheet ( template , c("sheet1","sheet2") )
# setStyleAction(template,XLC$"STYLE_ACTION.NONE")
Data <- data.frame(
  a = 1:10,
  b = 11:20
)

setDataFormatForType(template, type = XLC$DATA_TYPE.NUMERIC, format = "0.00"  )
# list22$`Brand Equity` <- as.numeric(list22$`Brand Equity`)
# list22$`Purchase Intent` <- as.numeric(list22$`Purchase Intent`)

csHeader <- createCellStyle(template,  name = "header10")
setFillPattern(csHeader, fill = XLC$BORDER.DOUBLE)
setFillForegroundColor(csHeader, color = XLC$COLOR.DARK_RED)

# setCellFormula(object = template, sheet = (paste0("sheet",i)), row = c(2:4),col = c(1:3), formula =  )

setCellStyle(template, sheet = "sheet1", row = 1,
             col = c(1:2),  cellstyle = csHeader)
setCellStyle(template, sheet = "sheet2", row = 1,
             col = c(1:2),  cellstyle = csHeader)

  for (i in 1:2)
  {
                 setColumnWidth(template, sheet = (paste0("sheet",i)), column = c(1:3), width = 15800)
    writeWorksheet ( template , data = Data, sheet = (paste0("sheet",i)), startRow = 1 , startCol = 1 ,
                     header = TRUE )
  }


saveWorkbook ( template )

I obtain enter image description here

and enter image description here

It does not seem to pass my argument about the color of the cell. Any ideas ? Moreover is there a way to write transform the numbers in percentages ? So 1 for instance would be 100%, 2 would be 200% etc...

1

There are 1 answers

0
krish On

For converting the numbers into percentage, you can write a function similar to this one:

addformatperc<-function(num,roundlevel){
  betternum<-paste(prettyNum(round(num*100,roundlevel),big.mark = ","),"%",sep="")
  return(betternum)
}
#Output
addformatperc(1,0)
[1] "100%"