简体   繁体   English

使用xlsx(R包)格式化具有相同单元格样式的整个数据框

[英]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. 我有一个具有可变列数的数据框,我想使用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. 但是当我尝试在colStyle中设置colStyle时,我不知道如何创建一个与我的数据框的列数长度相同的pct列表。 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): 你必须创建一个CellStyle对象列表 ,它将是这样的(假设df是一个data.frame对象):

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 我找到了一个关于在这个博客上编写xlsx文件的有用示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM