当前位置: 动力学知识库 > 问答 > 编程问答 >

Format entire data frame with the same cell style using xlsx (R package)

问题描述:

I have a data frame with a variable number of columns and I would like to format the entire data frame with the same cell style using xlsx. I have created the cell style:

pct <- CellStyle(soccer, dataFormat=DataFormat("0.0%"))

But when I try to set the colStyle in addDataFrame, I'm not sure how to create a list of pct that is the same length as the number of columns of my data frame. I've tried something like this:

addDataFrame(x = df, sheet = my.sheet, startRow = i, colStyle=rep(pct, length(df)))

It doesn't work though since I know that each element must have a name that corresponds to the column number.

网友答案:

I had the same issue; you have to create a list of CellStyle objects, and it will be something like that (supposing that df is a data.frame object):

pct <- CellStyle(soccer, dataFormat=DataFormat("0.0%"))

dfColIndex <- rep(list(pct), dim(df)[2]) 
names(dfColIndex) <- seq(1, dim(df)[2], by = 1)

addDataFrame(x = df, sheet = my.sheet, startRow = i, colStyle= dfColIndex)

I named the list elements with the column number, even if it seems from the help page that is not mandatory (but without them it didn't work for me).

The code I provided it's a short version of

 dfColIndex <- list("1" = pct, 
                    "2" = pct, 
                    "3" = pct, 
                    ... # and so on, for every column of you dataframe)

I found a useful example about writing xlsx files at this blog

分享给朋友:
您可能感兴趣的文章:
随机阅读: