当你不知道列索引(有没有更好的方法)时,从R到Excel(包= xlsx)列格式?

我一直在使用xlsx软件包作为从R输出输出的一种方式,而当你不知道(事先)哪种列将以何种格式进行格式化时,我遇到了设置列数据格式的问题。

顺便说一下,我发现这个贸易绘图仪上最棒的post对我来说至关重要。 我强烈推荐它: 来自Tradeblotter博客的背景文章

在我的使用案例中,我每月都会生成报告,每个月要导出的data.frame将增加1列或更多列(然后需要正确格式化)。 我不想手动进入并在代码中设置列名,但宁愿让R为我计算列数,然后向xlsx代码提供一个索引向量。

在研究了colStyle列表对象的结构之后,我能够创build这个解决方法,但是我必须相信有更好的方法,我正在寻找一些帮助来find它。

提前致谢! 克里斯

require(xlsx) iris$cost <- rbinom(nrow(iris), 3, .85)+1000 iris$cost2 <- rbinom(nrow(iris), 3, .85)+1000 test <- createWorkbook() # Define some cell styles within that workbook csSheetTitle <- CellStyle(test) + Font(test, heightInPoints=18, isBold=TRUE) csdollar <- CellStyle(test, dataFormat=DataFormat("$###,##0.00")) # ... for ratio results csdefault <- CellStyle(test, dataFormat=DataFormat("0.00")) # ... for ratio results csTableColNames <- CellStyle(test) + Font(test, isBold=TRUE) + Alignment(wrapText=TRUE, h="ALIGN_CENTER") + Border(color="black", position=c("TOP", "BOTTOM"), pen=c("BORDER_THIN", "BORDER_THICK")) csTableColNames <- CellStyle(test) + Font(test, isBold=TRUE) + Alignment(wrapText=TRUE, h="ALIGN_CENTER") + Border(color="black", position=c("TOP", "BOTTOM"), pen=c("BORDER_THIN", "BORDER_THICK")) sheet <- createSheet(test, sheetName = names(ytddflist)[i]) rows <- createRow(sheet,rowIndex=1) sheetTitle <- createCell(rows, colIndex=1) setCellValue(sheetTitle[[1,1]], "iris data with cost ($)") setCellStyle(sheetTitle[[1,1]], csSheetTitle) default.format = list( '1'=csdefault, '2'=csdefault, '3'=csdefault, '4'=csdefault) dollar.format =list( 'notused'=csdollar) # here is where I create the dollar.format list object that will eventuall be fed to addDataFrame dollar.format.list <- rep(dollar.format, 2) names(dollar.format.list) <- as.character(c(6, 7)) addDataFrame(iris, sheet, startRow=3, startColumn=1, colStyle=c(default.format,dollar.format.list), colnamesStyle = csTableColNames) saveWorkbook(test , "iriswithdollarx2.xlsx") 

我不知道你是否还需要它,但我花了一些时间与xlsx包“打架”,为了从R中产生包含大量表的Excel文件,事先不知道列的数量,所以这里是我的策略。

关键是创buildcolStyle列表; 代替

 default.format = list( '1'=csdefault, '2'=csdefault, '3'=csdefault, '4'=csdefault) 

一个快捷方式是将列表创build为list对象的向量,然后将名称分配给其元素:

 default.format <- rep(list(csdefault), 4) # style for the first 4 columns dollar.format <- rep(list(csdollar), (dim(iris)[2]-length(default.format))) # style for remaining columns format <- c(default.format, dollar.format) # create the colStyle list names(format) <- seq(1, dim(iris)[2], by = 1) # assign names to list elements # add dataframe to the workbook addDataFrame(iris, sheet, startRow=3, startColumn=1, colStyle=format, colnamesStyle = csTableColNames)