如何在xlsx中编写并修改单元格的格式

时间:2017-01-03 16:28:37

标签: r excel xlsx xlconnect

运行此代码后

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 )

我获得enter image description here

enter image description here

似乎没有通过我关于细胞颜色的论证。有任何想法吗 ?还有一种方法可以用百分比来改变数字吗?因此,例如1将是100%,2将是200%等...

1 个答案:

答案 0 :(得分:0)

要将数字转换为百分比,您可以编写类似于此的函数:

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