【问题标题】:how to write in xlsx and modifying the format of the cells如何在 xlsx 中写入并修改单元格的格式
【发布时间】:2017-01-03 16:28:36
【问题描述】:

运行这段代码后

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 )

我得到

它似乎没有通过我关于单元格颜色的论点。有任何想法吗 ?此外,有没有办法以百分比形式转换数字?因此,例如 1 将是 100%,2 将是 200% 等等...

【问题讨论】:

  • 看起来您需要首先将数据写入单元格,然后然后将单元格样式设置为您想要的任何样式。目前,您可以很好地设置单元格的样式,然后使用 XLConnect 的 writeWorksheet() 的默认样式覆盖它们。换句话说,将您的for 循环移动到您调用setDataFormat() 之后。

标签: r excel xlsx xlconnect


【解决方案1】:

为了将数字转换成百分比,你可以写一个类似的函数:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-27
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多