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
pct <- CellStyle(soccer, dataFormat=DataFormat("0.0%")) dfColIndex <- rep(list(pct), dim(df)) names(dfColIndex) <- seq(1, dim(df), 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